package com.dhcc.DRGsHosp.facade.impl;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.inject.Named;
import javax.servlet.http.HttpServletResponse;

import net.sf.ehcache.CacheManager;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.openkoala.koala.commons.InvokeResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.dhcc.DRGsHosp.application.ClinicGroupApplication;
import com.dhcc.DRGsHosp.application.CostSubApplication;
import com.dhcc.DRGsHosp.application.DRGVersionApplication;
import com.dhcc.DRGsHosp.application.DRGsApplication;
import com.dhcc.DRGsHosp.application.DailyRecordApplication;
import com.dhcc.DRGsHosp.application.DepartmentApplication;
import com.dhcc.DRGsHosp.application.DrgCommonApplication;
import com.dhcc.DRGsHosp.application.DrgsServiceApplication;
import com.dhcc.DRGsHosp.application.FieldMapApplication;
import com.dhcc.DRGsHosp.application.FileUploadApplication;
import com.dhcc.DRGsHosp.application.HospInfoApplication;
import com.dhcc.DRGsHosp.application.MedicalRecordApplication;
import com.dhcc.DRGsHosp.application.MedinsApplication;
import com.dhcc.DRGsHosp.application.PatientDrgApplication;
import com.dhcc.DRGsHosp.application.QuotaManageApplication;
import com.dhcc.DRGsHosp.application.WardApplication;
import com.dhcc.DRGsHosp.application.XPathParseApplication;
import com.dhcc.DRGsHosp.core.domain.ClinicGroup;
import com.dhcc.DRGsHosp.core.domain.CostSub;
import com.dhcc.DRGsHosp.core.domain.DRGVersion;
import com.dhcc.DRGsHosp.core.domain.DRGs;
import com.dhcc.DRGsHosp.core.domain.Department;
import com.dhcc.DRGsHosp.core.domain.HospInfo;
import com.dhcc.DRGsHosp.core.domain.Medins;
import com.dhcc.DRGsHosp.core.domain.MrAppendPage;
import com.dhcc.DRGsHosp.core.domain.MrBaseInfo;
import com.dhcc.DRGsHosp.core.domain.MrDiagnose;
import com.dhcc.DRGsHosp.core.domain.MrExpense;
import com.dhcc.DRGsHosp.core.domain.MrIpInfo;
import com.dhcc.DRGsHosp.core.domain.MrOperation;
import com.dhcc.DRGsHosp.core.domain.PatientDrg;
import com.dhcc.DRGsHosp.core.domain.PatientDrgPrimary;
import com.dhcc.DRGsHosp.core.domain.Ward;
import com.dhcc.DRGsHosp.facade.DepGroupFacade;
import com.dhcc.DRGsHosp.facade.FileUploadFacade;
import com.dhcc.DRGsHosp.facade.GroupServiceFacade;
import com.dhcc.DRGsHosp.facade.XPathParseFacade;
import com.dhcc.DRGsHosp.facade.XmlStructureFacade;
import com.dhcc.DRGsHosp.facade.dto.DepGroupDTO;
import com.dhcc.DRGsHosp.facade.dto.ManageSummaryDTO;
import com.dhcc.DRGsHosp.facade.impl.assembler.ManageSummaryAssembler;
import com.dhcc.DRGsHosp.infra.util.Arith;
import com.dhcc.DRGsHosp.infra.util.DrgsIndex;
import com.dhcc.DRGsHosp.infra.util.ExcelUtil;
import com.dhcc.DRGsHosp.infra.util.GlobalData;
import com.dhcc.DRGsHosp.infra.util.StringUtils;
import com.dhcc.DRGsHosp.infra.util.jdbf.DBFReader;

/**
 * @title		:FileUploadFacadeImpl.java
 * @description	: 文件上传
 * @author		:mazhaoyan
 * @date		:2015年5月19日
 * @version     :1.0
 * @copyright   :DHCC 2013-2015
 */
@Named("drgsHospFacadeImpl18")
public class FileUploadFacadeImpl implements FileUploadFacade {
	private static final Logger logger = LoggerFactory.getLogger(FileUploadFacadeImpl.class);//日志记录
	//依赖注入
	@Autowired
	private DepGroupFacade  depGroupFacade;
	@Autowired
	private DepartmentApplication  departmentApplication;
	@Autowired
	private WardApplication wardApplication;	
	@Autowired
	private ClinicGroupApplication  clinicGroupApplication;
	@Autowired
	private QuotaManageApplication  quotaManageApplication;
	@Autowired
	private MedicalRecordApplication medicalRecordApplication;
	@Autowired
	private DRGsApplication drgsApplication;
	@Autowired
	private PatientDrgApplication patientDrgApplication;
	@Autowired
	private MedinsApplication medinsApplication;
	@Autowired
	private DailyRecordApplication dailyRecordApplication;
	@Autowired
	private DRGVersionApplication drgVersionApplication;
	@Autowired
	private XmlStructureFacade xmlStructureFacade;
	@Autowired
	private XPathParseFacade xPathParseFacade;
	@Autowired
	public FileUploadApplication fileUploadApplication;
	@Autowired 
	private CostSubApplication costSubApplication;
	@Autowired 
	private GroupServiceFacade groupServiceFacade;
	@Autowired
	private DrgsServiceApplication drgsServiceApplication;
	@Autowired
	private FieldMapApplication fieldMapApplication;
	@Autowired
	private XPathParseApplication xPathParseApplication;
	@Autowired
    private CacheManager cacheManager;
	
	@Autowired
	private DrgCommonApplication  drgCommonApplication;

	@Autowired
	private HospInfoApplication hospInfoApplication;
	
	//注入结束
	
	private String message="";//返回前台的信息
	private String detail="";//进度进行详情
	private String time="";//剩余时间
	private long mdStartTime=0;//开始时间
	private int all = 1;//总数
	private int cur = 0;//当前数
	
	public  Integer allCnt;//总病例数
	public  Integer consumeCnt;//消费个数
	
	Map<String,Integer> fieldMap = new HashMap<String,Integer>();//字段位置Map
	List<Map<String,Object>> keyFieldMap = new LinkedList<Map<String,Object>>();//基本信息字段映射关系
	List<Map<String,Object>> baseInfoFieldMap = new LinkedList<Map<String,Object>>();//基本信息字段映射关系
	List<Map<String,Object>> ipInfoFieldMap = new LinkedList<Map<String,Object>>();//住院信息字段映射关系
	List<Map<String,Object>> appendInfoFieldMap = new LinkedList<Map<String,Object>>();//附页信息字段映射关系
	List<Map<String,Object>> mainDiagFieldMap = new LinkedList<Map<String,Object>>();//主要诊断信息字段映射关系
	Map<String,List<Map<String,Object>>> otherDiagMap = new HashMap<String,List<Map<String,Object>>>();
	List<Map<String,Object>> mainOperFieldMap = new LinkedList<Map<String,Object>>();//主要手术信息字段映射关系
	Map<String,List<Map<String,Object>>> otherOperMap = new HashMap<String,List<Map<String,Object>>>();
	List<Map<String,Object>> expInfoFieldMap = new LinkedList<Map<String,Object>>();//费用信息字段映射关系
	
	/**
	 * 
	 *  @Description：首页数据文件上传
	 *  @Author mazhaoyan  
	 *  @see com.dhcc.DRGsHosp.facade.FileUploadFacade#importMedicalRecord(java.lang.String, java.lang.String, int, int)
	 */
	@Override
	public InvokeResult importMedicalRecord(String filePath, String context,int cur,int all) {
		if(cur>1){
			//暂停3秒
			try {
				Thread.sleep(3500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		consumeCnt = 0;//消费个数初始化
		
		GlobalData.percent=0;//进度完成百分比
		GlobalData.fileInfo="";//正在处理文件的信息
		GlobalData.saveInfo="";//保存信息
		GlobalData.dataInfo="";//处理数据信息
		GlobalData.errorInfo="";//错误信息
		GlobalData.stateInfo="";//状态信息 error-错误  done-完成一个  finish-结束
		String extension=filePath.substring(filePath.lastIndexOf("."));//扩展名
		extension = extension==null?"":extension ;
		long startTime=new Date().getTime();
		mdStartTime = startTime;
		//所有科室
		List<Department> depList = departmentApplication.findAllDepartment();
		Map<String, String> depMap = new HashMap<String, String>();//科室名称代码信息
		Map<String, String> depMapCodeName = new HashMap<String, String>();//科室名称代码信息
		for (Department dep : depList) {
			depMap.put(dep.getDepName(), dep.getDepCode());
			depMapCodeName.put(dep.getDepCode(),dep.getDepName());
		}
		InvokeResult parseStatus = new InvokeResult();
		switch (extension.toLowerCase()) {
		//Excel格式数据
		case ".xlsx":
		case ".xls":
			parseStatus = parseXlsFile(filePath);
			break;
		//xml格式数据
		case ".xml":
			parseStatus = parseXmlFile(filePath);
			break;
		//DBF格式数据
		case ".dbf":
			parseStatus = parseDBFFile(filePath);
			break;
		//CSV格式数据
		case ".csv":
			parseStatus = parseCsvFile(filePath);
			break;
		default:
			{
				GlobalData.fileInfo = "只支持xlsx,xml,dbf,csv格式的文件,请重新上传";
			}
		}
			
		File tempFile = new File(filePath);
		if(tempFile.exists())  {
			tempFile.delete();       
		}
		//如果解析遇到错误，中断执行
		if (parseStatus.isHasErrors()) {
			return parseStatus;
		}
		
		GlobalData.percent=100;
		if(cur==all){
			GlobalData.stateInfo = "finish";
        }
		return InvokeResult.success();
	}
	/**
	 * 
	 *  parseXlsFile.  
	 *  @Description：解析Excel文件
	 *  @Author mazhaoyan
	 *  @param filePath
	 *  @return 
	 *  @Date:2018年3月28日下午5:32:08
	 */
	private InvokeResult parseXlsFile(String filePath) {
		Map<String,Object> initMap = null;//获取初始化数据 
		try {
			initMap = xmlStructureFacade.getInitProperty();//获取初始化数据
            //从数据库中获取 映射关系
			initFieldMapInfo();
            GlobalData.fileInfo = "正在解析文件……";
            Sheet sheet = ExcelUtil.readExcelSheet(filePath,0);
    		Row row = null;
    		row = sheet.getRow(0);//title 行数据
    		int colNum = row.getPhysicalNumberOfCells();//列数
    		int rowNum =sheet.getLastRowNum();//最大行数
    		allCnt = rowNum-1;
    		if(allCnt<0){
				logger.error("此文件没有有效数据");
				GlobalData.stateInfo = "error";
				return InvokeResult.failure("此文件没有有效数据");
			}
    		//线程仓库
			Storage storage = new Storage();
			ExecutorService parseMrDataPools = Executors.newFixedThreadPool(10);//解析获取首页数据线程池
			ExecutorService SaveMrDataPools = Executors.newFixedThreadPool(10);//首保存首页数据线程池
			//读取excel表头
    		for (int rn = 0; rn <= rowNum; rn++) {// 【<=】 是正确的 不要动
    			row = sheet.getRow(rn);//行数据
    			String[] colArr = new String[colNum];
    			for (int cn = 0; cn < colNum; cn++) {// 【<】 是正确的 不要动
    				Cell cell = row.getCell(cn);
    				String cellvalue = "";
    		        if (cell != null) {
    		        	int cellType = cell.getCellType();
    		        	if(cellType == Cell.CELL_TYPE_NUMERIC){
    		                // 判断当前的cell是否为Date
    		                if (DateUtil.isCellDateFormatted(cell)) {
    		                    // 如果是Date类型则，转化为Data格式
    		                    Date date = cell.getDateCellValue();
    		                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    		                    cellvalue = sdf.format(date);
    		                }else { // 如果是纯数字 
    		                    // 取得当前Cell的数值
    		                    cellvalue = String.valueOf(cell.getNumericCellValue());
    		                }
    		        	}else if(cellType == Cell.CELL_TYPE_STRING){
    		        		cellvalue = String.valueOf(cell.getStringCellValue());
						}
    		        }
    				if(rn==0){//title 行
    					fieldMap.put(cellvalue,cn);
    				}else{//实际数据行
    					colArr[cn] = cellvalue;
    				}
    			}
    			if(rn>0){
    				parseMrDataPools.execute(new ParseMrdataOther(colArr,storage,initMap));//解析获取首页数据
    				SaveMrDataPools.execute(new SaveMrData(storage,initMap));//保存首页数据
    			}
    		}
			parseMrDataPools.shutdown();
			SaveMrDataPools.shutdown();
			parseMrDataPools.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
			SaveMrDataPools.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
            //一行一行的解析数据
            cacheManager.clearAll();//清楚缓存
		} catch (Exception e) {
			logger.error(e.getMessage());
			GlobalData.errorInfo = "数据解析异常";
			GlobalData.stateInfo = "error";
			return InvokeResult.failure("数据解析异常");
		}
		return InvokeResult.success();
	}
	
	
	/**  
	 *  parseCsvFile.  
	 *  @Description：解析csv文件
	 *  @Author mazhaoyan
	 *  @param filePath
	 *  @return 
	 *  @Date:2018年1月19日上午9:00:31   
	 */
	private InvokeResult parseCsvFile(String filePath) {
		BufferedReader brParse = null;//解析
		DataInputStream in =null;
		int lCsv=0,allCsv=0;//文件总行数,当前行数
		Map<String,Object> initMap = null;//获取初始化数据
		
        String line ="";//临时字符串  
        String csvSplitBy = ",(?=([^\"]*\"[^\"]*\")*[^\"]*$)";//分隔符
        try {
			in = new DataInputStream(new FileInputStream(new File(filePath)));//输入流
			brParse = new BufferedReader(new InputStreamReader(in,"GBK"));//解析  
            //一行一行的解析数据
            while((line = brParse.readLine()) != null){
            	allCsv++;
            }
		} catch (Exception e) {
			logger.error(e.getMessage());
			GlobalData.errorInfo = "读取行数异常";
			GlobalData.stateInfo = "error";
			return InvokeResult.failure("读取行数异常");
		}
		finally {
			try {
				brParse.close();
				in.close();
			} catch (IOException e) {
				logger.error(e.getMessage());
				GlobalData.errorInfo = "文件关闭失败";
				GlobalData.stateInfo = "error";
				return InvokeResult.failure("文件关闭失败");
			}
		}
        allCnt = allCsv-1;
		if(allCnt<=0){
			logger.error("此文件没有有效数据");
			GlobalData.stateInfo = "error";
			return InvokeResult.failure("此文件没有有效数据");
		}
		try {
			in = new DataInputStream(new FileInputStream(new File(filePath)));//输入流
			brParse = new BufferedReader(new InputStreamReader(in,"GBK"));//解析  
			initMap = xmlStructureFacade.getInitProperty();//获取初始化数据
            //从数据库中获取 映射关系
			initFieldMapInfo();
            GlobalData.fileInfo = "正在解析文件……";
            //线程仓库
			Storage storage = new Storage();
			ExecutorService parseMrDataPools = Executors.newFixedThreadPool(10);//解析获取首页数据线程池
			ExecutorService SaveMrDataPools = Executors.newFixedThreadPool(10);//首保存首页数据线程池
            //一行一行的解析数据
            while((line = brParse.readLine()) != null){
            	lCsv++;
            	if(lCsv>1){//第一行是title 不处理 从第二行处理
            		String [] filedContent = line.split(csvSplitBy); //字段内容
            		parseMrDataPools.execute(new ParseMrdataOther(filedContent,storage,initMap));//解析获取首页数据
    				SaveMrDataPools.execute(new SaveMrData(storage,initMap));//保存首页数据
            	}else{//第一行
            		//文件头-- 记录字段名和位置
            		String [] fileds = line.split(csvSplitBy); 
            		for(int i = 0;i<fileds.length;i++){
            			fieldMap.put(fileds[i],i);
                    }
            	}
            }
            parseMrDataPools.shutdown();
			SaveMrDataPools.shutdown();
			parseMrDataPools.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
			SaveMrDataPools.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
            cacheManager.clearAll();//清楚缓存
		} catch (Exception e) {
			logger.error(e.getMessage());
			GlobalData.errorInfo = "数据解析异常";
			GlobalData.stateInfo = "error";
			return InvokeResult.failure("数据解析异常");
		}
		finally {
			try {
				brParse.close();
				in.close();
			} catch (IOException e) {
				logger.error(e.getMessage());
				GlobalData.errorInfo = "文件关闭失败";
				GlobalData.stateInfo = "error";
				return InvokeResult.failure("文件关闭失败");
			}
		}
		return InvokeResult.success();
	}
	/**
	 * 
	 * @methodname    :parseXmlFile
	 * @description   : 使用ztree结构解析xml 数据
	 * @param         :
	 * @author        :mazhaoyan
	 * @return        :
	 * @date          :2017年6月13日
	 */
	@SuppressWarnings("unchecked")
	private InvokeResult parseXmlFile(String filePath){
    	GlobalData.fileInfo = "正在解析文件……";
    	try {
	    	//创建SAXReader对象  
	    	SAXReader reader = new SAXReader();  
	    	//读取文件 转换成Document
	    	Document document = reader.read(new File(filePath));
	    	//获取根节点元素对象  
			Element root = document.getRootElement();
			//*************** 下面要改
			InputStream propInputStream = DrawDataFromHisFacadeImpl.class.getResourceAsStream("/nodeconfig.properties");
			Properties properties = new Properties();
			properties.load(propInputStream);
			String repeatNode = properties.getProperty("mr_node_address");
			if(!StringUtils.hasLength(repeatNode)){
				logger.error("REPEAT_NODE is null 请配置REPEAT_NODE");
				GlobalData.stateInfo = "error";
				return InvokeResult.failure("REPEAT_NODE is null");
			}
			Map<String,Object> initMap = xmlStructureFacade.getInitProperty();
			Map<String,Object> xPathMap = xPathParseApplication.getMrXPathMap("xmlFile");
			//获取重复节点
			List<Element> nodeChild = root.selectNodes(repeatNode);
			allCnt = nodeChild.size();
			if(allCnt<=0){
				logger.error("重复路径为 "+ repeatNode+ " 此路径下没有数据");
				GlobalData.stateInfo = "error";
				return InvokeResult.failure("路径下没有合法节点");
			}
			//线程仓库
			Storage storage = new Storage();
			ExecutorService parseMrDataPools = Executors.newFixedThreadPool(10);//解析获取首页数据线程池
			ExecutorService SaveMrDataPools = Executors.newFixedThreadPool(10);//首保存首页数据线程池
			for(Element node: nodeChild){
				parseMrDataPools.execute(new ParseMrdataXML(node,storage,initMap,xPathMap));//解析获取首页数据
				SaveMrDataPools.execute(new SaveMrData(storage,initMap));//保存首页数据
			}
			parseMrDataPools.shutdown();
			SaveMrDataPools.shutdown();
			parseMrDataPools.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
			SaveMrDataPools.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
			cacheManager.clearAll();
    	}catch(Exception e){	
    		logger.error(e.getMessage());
    		GlobalData.stateInfo = "error";
    		return InvokeResult.failure(e.getMessage());
    	}finally {
    		File tempFile = new File(filePath);
			if(tempFile.exists())  {  
				tempFile.delete();       
			}
		}
		return InvokeResult.success();
	}
	
	/**
	 * 
	 *  parseDBFFile.  
	 *  @Description：解析DBF文件
	 *  @Author mazhaoyan
	 *  @param filePath
	 *  @return 
	 *  @Date:2018年1月19日下午9:02:39
	 */
	private InvokeResult parseDBFFile(String filePath) {
		//读取DBF文件
		InputStream inputStreamParse = null;//输入流
		DBFReader dbfReaderParse = null;//解析
		Map<String,Object> initMap = null;//获取初始化数据
		int dbfAll = 0;
		try {
			//读取DBF文件
			inputStreamParse = new FileInputStream(filePath);
			dbfReaderParse = new DBFReader(inputStreamParse);
			while ( dbfReaderParse.hasNextRecord() ) {
				dbfAll++;
				dbfReaderParse.nextRecord(Charset.forName("GBK"));
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			GlobalData.errorInfo = "读取行数异常";
			GlobalData.stateInfo = "error";
			return InvokeResult.failure("读取行数异常");
		}finally {
			try {
				dbfReaderParse.close();
				inputStreamParse.close();
			} catch (Exception e) {
				logger.error(e.getMessage());
				GlobalData.errorInfo = "流关闭异常";
				GlobalData.stateInfo = "error";
				return InvokeResult.failure("流关闭异常");
			}
		}
		allCnt = dbfAll;
		if(allCnt<=0)
		{
			logger.error("此文件没有有效数据");
			GlobalData.stateInfo = "error";
			return InvokeResult.failure("此文件没有有效数据");
		}
		try {
			//读取DBF文件
			inputStreamParse = new FileInputStream(filePath);
			dbfReaderParse = new DBFReader(inputStreamParse);
			for (int i = 0; i < dbfReaderParse.getFieldCount(); i++) {
				fieldMap.put(dbfReaderParse.getField(i).getName(),i);
			}
			//从数据库中获取 映射关系
			initFieldMapInfo();
			initMap = xmlStructureFacade.getInitProperty();//获取初始化数据
            GlobalData.fileInfo = "正在解析文件……";
          //线程仓库
			Storage storage = new Storage();
			ExecutorService parseMrDataPools = Executors.newFixedThreadPool(10);//解析获取首页数据线程池
			ExecutorService SaveMrDataPools = Executors.newFixedThreadPool(10);//首保存首页数据线程池
			while ( dbfReaderParse.hasNextRecord() ) {
				Object[] rowData = dbfReaderParse.nextRecord(Charset.forName("GBK"));
				parseMrDataPools.execute(new ParseMrdataOther(rowData,storage,initMap));//解析获取首页数据
				SaveMrDataPools.execute(new SaveMrData(storage,initMap));//保存首页数据
			}
			parseMrDataPools.shutdown();
			SaveMrDataPools.shutdown();
			parseMrDataPools.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
			SaveMrDataPools.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
			cacheManager.clearAll();
		} catch (Exception e) {
			logger.error(e.getMessage());
			GlobalData.errorInfo = "数据解析异常";
			GlobalData.stateInfo = "error";
			return InvokeResult.failure("数据解析异常");
		}
		finally {
			try {
				dbfReaderParse.close();
				inputStreamParse.close();
			} catch (Exception e) {
				logger.error(e.getMessage());
				GlobalData.errorInfo = "流关闭异常";
				GlobalData.stateInfo = "error";
				return InvokeResult.failure("流关闭异常");
			}
		}
		return InvokeResult.success();
	}
	/**
	 * @methodname    :finish
	 * @description   :完成状态
	 * @param         :s:已完成 or 已中断
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年7月3日
	 */
	private void finish(String s) {
		//暂停2500毫秒
    	try {
			Thread.sleep(4000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    	message=s;
    	//暂停5000毫秒
    	try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    	GlobalData.percent=0;
    	detail="";
    	message="";
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.FileUploadFacade#importDRGs(java.lang.String)
	 */
    @Override
    public InvokeResult importDRGs(String filePath) {
        message="";
        GlobalData.percent=0;
        detail="";
        String errorRow = "0";
        String errorCell="0";
        String notInMedicalRecordMsg = "";

        List<PatientDrg> patientDRGs = new ArrayList<PatientDrg>();

        //=======安贞病案号补0个性化========
		boolean isAnzhen = false;
		String[] zero = {"","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000"};
        List<HospInfo> hospInfos = hospInfoApplication.findAllHosp();
		for (int i = 0; i < hospInfos.size(); i++) {
			//判断是否北京安贞
			if (hospInfos.get(i)!=null && hospInfos.get(i).getHospName()!=null && hospInfos.get(i).getHospName().contains("北京安贞")){
				isAnzhen = true;
			}
		}
		//================================

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(filePath);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        String extension=filePath.substring(filePath.lastIndexOf("."));//扩展名
        System.out.println("===drg文件扩展名："+extension);

        //定义存储id
        String mrNotemp1 = null ;
        Date outDatetemp1 = null;
        SimpleDateFormat outDatetemp2=new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat outDatetemp3=new SimpleDateFormat("yyyy-MM");
        String dd = null;
        Date outDate=null;
        // 判断改月数据是否存在
        boolean flag ;
        List<String> mrIDList = new ArrayList<String>();
        //medicalRecords = uploadFuncService.readId();
        List<String> excelDrg = new ArrayList<String>();
        /**
         * drgLISt
         */
        List<String> drgList = new ArrayList<String>();
        List<DRGs> rlist = drgsApplication.findAllDRGs(new DRGs());
        if (!rlist.isEmpty()) {
            for (DRGs drgs:rlist) {
                String drgCode= drgs.getDrgCode();
                drgList.add(drgCode);
            }
        }

        String drgVersion = drgVersionApplication.getLatestDRGVersion("北京");//获取北京最新DRG版本号
        String verRegion=drgVersionApplication.getDrgRegionByVerCode(drgVersion);
        try {
            Workbook workbook=null;
            Sheet sheet=null;
            Row row=null;
            Row firstrow=null;
            Cell cell=null;
            if (extension.equals(".xls")) {
                try {
                    workbook=new HSSFWorkbook(fileInputStream);
                    sheet=(HSSFSheet) workbook.getSheetAt(0);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if(extension.equals(".xlsx")){
                try {
                    workbook=new XSSFWorkbook(fileInputStream);
                    sheet=(XSSFSheet)workbook.getSheetAt(0);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                String errorInfoString = "上传的文件格式有误，请检查后重新上传";
                message = "上传的文件格式有误，请检查后重新上传";
                System.out.println("==========="+errorInfoString);

                return InvokeResult.failure(errorInfoString);
            }

            //读取表头数据
            message="读取表数据";
            firstrow = sheet.getRow(0);
            int colNum = firstrow.getPhysicalNumberOfCells();
            String[] title = new String[colNum];
            System.out.println("-====================表头列数："+firstrow.getLastCellNum());
            for (int firstnumCells = 0; firstnumCells < firstrow.getLastCellNum(); firstnumCells++) {

                cell = firstrow.getCell((short) firstnumCells);
                title[firstnumCells] = cell.getStringCellValue();
                detail = cell.getStringCellValue();

            }


            for (int numRows = 1; numRows <= sheet.getLastRowNum() ; numRows++) {
                row = sheet.getRow(numRows);
                for(int numCells = 0; numCells < row.getLastCellNum(); numCells++){
                    String titleString = title[numCells];
                    cell = row.getCell((short)numCells);
                    if("出院日期".equals(titleString)){
                        if(cell==null){
                            outDate = null;
                        }else{
                            outDate = cell.getDateCellValue();
                        }
                        break;
                    }
                }
                if(null != outDate){
                    break;
                }
            }
            String mm = outDatetemp3.format(outDate);
            // 根据日期判断首页数据是否存在
            flag = medicalRecordApplication.isMedicalRecordsExistByDate(mm);
            if(!flag){
                String errorInfoString = "您还没有上传"+mm+"的首页数据，请先上传首页数据。";
                message = errorInfoString;
                finish("已中断");
                return InvokeResult.failure(message);
            }

            //读取表单数据
            for (int numRows = 1; numRows <= sheet.getLastRowNum(); numRows++) {
                row = sheet.getRow(numRows);
                errorRow = String.valueOf(numRows);
                PatientDrg patientDRG = new PatientDrg();

                for (int numCells = 0; numCells < row.getLastCellNum(); numCells++) {
                    cell = row.getCell((short) numCells);
                    String aaString=null;
                    aaString = title[numCells];
                    errorCell = String.valueOf(numCells);

                    switch (aaString) {
                        case "病案号":
                            if(cell==null){

                                mrNotemp1 = "";
                            }else{

                                row.getCell(numCells).setCellType(Cell.CELL_TYPE_STRING);
                                mrNotemp1 = row.getCell(numCells).getStringCellValue();

                                //北京安贞，不足十位的前面补0（因为首页结构化存储传过来的病案号是这样）
                                if (mrNotemp1 != null && isAnzhen){
                                    mrNotemp1 = zero[10-mrNotemp1.length()] + mrNotemp1;
                                }
                            }
                            break;
                        case "drg":
                            if(cell==null){
                                patientDRG.setPardrgCode("");
                                patientDRG.setNotinCode("");

                            }else{
                                String drgtemp = null;
                                if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                                    String aTemp = cell.getStringCellValue();
                                    if(aTemp.length()==3){//说明是QY的未分组病例
                                        patientDRG.setPardrgCode("");
                                        patientDRG.setNotinCode(aTemp);
                                    }else if(aTemp.matches("^\\d{4}$")){
                                        patientDRG.setPardrgCode("");
                                        patientDRG.setNotinCode(aTemp);
                                    }else if(aTemp.equals("0")||aTemp.equals("-")){
                                        patientDRG.setPardrgCode("");
                                        patientDRG.setNotinCode("0000");
                                    }else{
                                        patientDRG.setPardrgCode(cell.getStringCellValue()+"");
                                        drgtemp = cell.getStringCellValue();
                                        excelDrg.add(drgtemp);
                                    }

                                } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {

                                    row.getCell(numCells).setCellType(Cell.CELL_TYPE_STRING);
                                    String aTemp = row.getCell(numCells).getStringCellValue();

                                    if(aTemp.length()==3){//说明是QY的未分组病例
                                        patientDRG.setPardrgCode("");
                                        patientDRG.setNotinCode(aTemp);
                                    }else if(aTemp.matches("^\\d{4}$")){
                                        patientDRG.setPardrgCode("");
                                        patientDRG.setNotinCode(aTemp);
                                    }else if(aTemp.equals("0")||aTemp.equals("-")){
                                        patientDRG.setPardrgCode("");
                                        patientDRG.setNotinCode("0000");
                                    }else{
                                        patientDRG.setPardrgCode(aTemp);
                                        drgtemp = aTemp;
                                        excelDrg.add(drgtemp);
                                    }

                                }

                            }
                            break;
                        case "DRG":
                            if(cell==null){
                                patientDRG.setPardrgCode("");
                                patientDRG.setNotinCode("");

                            }else{
                                String drgtemp = null;
                                if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                                    String aTemp = cell.getStringCellValue();
                                    if(aTemp.length()==3){//说明是QY的未分组病例
                                        patientDRG.setPardrgCode("");
                                        patientDRG.setNotinCode(aTemp);
                                    }else if(aTemp.matches("^\\d{4}$")){
                                        patientDRG.setPardrgCode("");
                                        patientDRG.setNotinCode(aTemp);
                                    }else if(aTemp.equals("0")||aTemp.equals("-")){
                                        patientDRG.setPardrgCode("");
                                        patientDRG.setNotinCode("0000");
                                    }else{
                                        patientDRG.setPardrgCode(cell.getStringCellValue()+"");
                                        drgtemp = cell.getStringCellValue();
                                        excelDrg.add(drgtemp);
                                    }

                                } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {

                                    row.getCell(numCells).setCellType(Cell.CELL_TYPE_STRING);
                                    String aTemp = row.getCell(numCells).getStringCellValue();

                                    if(aTemp.length()==3){//说明是QY的未分组病例
                                        patientDRG.setPardrgCode("");
                                        patientDRG.setNotinCode(aTemp);
                                    }else if(aTemp.matches("^\\d{4}$")){
                                        patientDRG.setPardrgCode("");
                                        patientDRG.setNotinCode(aTemp);
                                    }else if(aTemp.equals("0")||aTemp.equals("-")){
                                        patientDRG.setPardrgCode("");
                                        patientDRG.setNotinCode("0000");
                                    }else{
                                        patientDRG.setPardrgCode(aTemp);
                                        drgtemp = aTemp;
                                        excelDrg.add(drgtemp);
                                    }

                                }


                            }
                            break;
                        case "出院日期":
                            if(cell==null){
                                outDatetemp1 = null;
                            }else{
                                //	patientDRG.setOutDate(cell.getDateCellValue());
                                outDatetemp1 = cell.getDateCellValue();
                                outDate= cell.getDateCellValue();
                                dd =outDatetemp2.format(outDatetemp1);
                            }
                            break;
                        case "MDC":
                            if(cell==null){
                                patientDRG.setMdc("");
                            }else{

                                if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                                    String aTemp = cell.getStringCellValue();

                                    if(aTemp.equals("0000")||aTemp.equals("0")||aTemp.equals("-")){
                                        patientDRG.setMdc("");
                                    }else{
                                        patientDRG.setMdc(cell.getStringCellValue()+"");
                                    }

                                } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {

                                    row.getCell(numCells).setCellType(Cell.CELL_TYPE_STRING);
                                    String aTemp = row.getCell(numCells).getStringCellValue();

                                    if(aTemp.equals("0000")||aTemp.equals("0")||aTemp.equals("-")){
                                        patientDRG.setMdc("");
                                    }else{
                                        patientDRG.setMdc(aTemp);

                                    }

                                }

                            }
                            break;

                        case "mdc":
                            if(cell==null){
                                patientDRG.setMdc("");
                            }else{

                                if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                                    String aTemp = cell.getStringCellValue();

                                    if(aTemp.equals("0000")||aTemp.equals("0")||aTemp.equals("-")){
                                        patientDRG.setMdc("");
                                    }else{
                                        patientDRG.setMdc(cell.getStringCellValue()+"");
                                    }

                                } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {

                                    row.getCell(numCells).setCellType(Cell.CELL_TYPE_STRING);
                                    String aTemp = row.getCell(numCells).getStringCellValue();

                                    if(aTemp.equals("0000")||aTemp.equals("0")||aTemp.equals("-")){
                                        patientDRG.setMdc("");
                                    }else{
                                        patientDRG.setMdc(aTemp);

                                    }

                                }

                            }
                            break;
                        case "版本":
                            if(cell==null){
                                patientDRG.setVerCode("");
                            }else{
                                if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                                    patientDRG.setVerCode(cell.getStringCellValue()+"");

                                } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                                    row.getCell(numCells).setCellType(Cell.CELL_TYPE_STRING);
                                    patientDRG.setVerCode(row.getCell(numCells).getStringCellValue());
                                }

                            }
                            break;
                        case "未入组原因":
                            if(cell==null){
                                patientDRG.setNotinCode("");
                            }else{
                                if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                                    patientDRG.setNotinCode(cell.getStringCellValue()+"");

                                } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                                    row.getCell(numCells).setCellType(Cell.CELL_TYPE_STRING);
                                    patientDRG.setNotinCode(row.getCell(numCells).getStringCellValue());
                                }

                            }
                            break;

                    }
                }
                //查找当前病案号和出院日期的医保数据在首页表中是否存在
                mrIDList = medicalRecordApplication.findMrIdByMrNoAndOutDate(mrNotemp1,"",dd);
                if(mrIDList!=null && mrIDList.size()>0){
                    //当前DRGs数据在首页表中有对应信息
                    if(patientDRG.getVerCode()==null){
                        patientDRG.setVerCode(drgVersion);//判断版本信息是否为空，如果为空取drg版本号添加版本信息
                    }
                    detail = mrNotemp1+": "+patientDRG.getPardrgCode();
                    if(!mrIDList.get(0).equals("")){
                        PatientDrgPrimary patientDrgPrimary=new PatientDrgPrimary();
                        patientDrgPrimary.setParid(mrIDList.get(0));
                        patientDrgPrimary.setVer_region(verRegion);
                        patientDRG.setPkId(patientDrgPrimary);
                        patientDRGs.add(patientDRG);
                    }
                }else{
                    notInMedicalRecordMsg += mrNotemp1+"-"+dd + "  ";
                }
                printProgress(sheet.getLastRowNum(), numRows);
            }

        } catch (Exception e) {
            e.printStackTrace();
            String errorInfoString = "表"+filePath+"的第"+errorRow+"行 "+"第"+errorCell+"列数据有问题，请检查后重新提交";
            message = errorInfoString;
            finish("已中断");
            return InvokeResult.failure(message);
        }finally{
            File tempFile = new File(filePath);
            if(tempFile.isFile() || tempFile.list().length == 0){
                System.out.println("============删除tempFile1=============");
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                tempFile.delete();
            }
        }

        if(flag){
            //检查ID,医保表和drg表对比
            try{
                //批量保存
                message = "正在保存,请稍候...<br/>";
                for (PatientDrg p : patientDRGs) {
                    patientDrgApplication.creatPatientDrg(p);
                }
                message += "下列数据为DRGs表中的住院病人,但首页表中没有该数据,可能由于病案号不存在或出院日期问题,请进行检查修改:<br/>"+notInMedicalRecordMsg;
                finish("已完成");
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return InvokeResult.success();
    }

    /* (non-Javadoc)
     * @see com.dhcc.DRGsHosp.facade.FileUploadFacade#importHCData(java.lang.String)
     */
    @Override
    public InvokeResult importHCData(String filePath,int cur,int all, String user_guid) {

		//=======安贞病案号补0个性化========
		boolean isAnzhen = false;
		String[] zero = {"","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000"};
		List<HospInfo> hospInfos = hospInfoApplication.findAllHosp();
		for (int i = 0; i < hospInfos.size(); i++) {
			//判断是否北京安贞
			if (hospInfos.get(i)!=null && hospInfos.get(i).getHospName()!=null && hospInfos.get(i).getHospName().contains("北京安贞")){
				isAnzhen = true;
			}
		}
		//================================

        //文件流对象  有异常时记得关闭
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(filePath);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        mdStartTime = new Date().getTime();
        message="";
        GlobalData.percent=0;
        detail="";
        String errorRow = "0";
        String errorCell="0";

        //医保表map，key为病案号+出院日期
        Map <String,Medins> medinsOutdateMap = new HashMap<String,Medins>();//map

        // 封装上传文件类型的属性
        // 封装上传文件名的属性
        String extension=filePath.substring(filePath.lastIndexOf("."));//扩展名
        System.out.println("===drg文件扩展名："+extension);


        //定义存储id
        String mrNotemp2 = null ;
        Date outDatetemp2 = null;
        SimpleDateFormat outDatetemp3=new SimpleDateFormat("yyyy-MM-dd");
        String outDateMedins = null;
        //入院日期存储变量
        Date inDatetemp2 = null;
        SimpleDateFormat inDatetemp3=new SimpleDateFormat("yyyy-MM-dd");
        String inDateMedins = null;
        List<String> list0 = new ArrayList<String>();//保存中途结算的数据
        List<String> listOutDateErr = new ArrayList<String>();//保存医保数据与首页表出院日期多条匹配的信息
        SimpleDateFormat outDatetemp4=new SimpleDateFormat("yyyy-MM");
        Date changOutdate = null;
        //用于存放 某个医保信息的病案号和出院日期对应的病案首页表的ID
        //一个医保数据可能对应多条首页数据
        List<String> mrIDList = new ArrayList<String>();

        try {

            Workbook workbook=null;
            Sheet sheet=null;
            Row row=null;
            Row firstrow=null;
            Cell cell=null;
            if (extension.equals(".xls")) {
                try {
                    workbook=new HSSFWorkbook(fileInputStream);
                    sheet=(HSSFSheet) workbook.getSheetAt(0);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if(extension.equals(".xlsx")){
                try {
                    workbook=new XSSFWorkbook(fileInputStream);
                    sheet=(XSSFSheet)workbook.getSheetAt(0);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                String errorInfoString = "上传的文件格式有误，请检查后重新上传";
                System.out.println("==========="+errorInfoString);
                return InvokeResult.failure(errorInfoString);
            }

            //读取表头数据
            message = "解析Excel    "+filePath.substring(filePath.lastIndexOf("\\")+1);
            firstrow = sheet.getRow(0);
            int colNum = firstrow.getPhysicalNumberOfCells();
            String[] title = new String[colNum];
            for (int firstnumCells = 0; firstnumCells < firstrow.getLastCellNum(); firstnumCells++) {
                System.out.println("==========一共有==============="+firstrow.getLastCellNum()+"列");
                cell = firstrow.getCell((short) firstnumCells);
                title[firstnumCells] = cell.getStringCellValue().replaceAll("\n", "");
                System.out.println("==========下面是title===============");
                detail = title[firstnumCells];
                System.out.println(title[firstnumCells]);
            }
            int rowTempMe = sheet.getLastRowNum();//获取总行数

            for (int numRows = 1; numRows <= rowTempMe ; numRows++) {
                row = sheet.getRow(numRows);
                for(int numCells = 0; numCells < row.getLastCellNum(); numCells++){
                    String titleString = title[numCells];
                    cell = row.getCell((short)numCells);
                    if("出院日期".equals(titleString)){
                        if(cell==null){
                            outDateMedins = null;
                        }else{
                            changOutdate = cell.getDateCellValue();
                        }
                        break;
                    }
                }
                if(null != changOutdate){
                    break;
                }
            }
            //查询构建首页数据的id的map和list
            String mm = outDatetemp4.format(changOutdate);
            boolean flag = medicalRecordApplication.isMedicalRecordsExistByDate(mm);
            if(!flag){
                String errorInfoString = "您还没有上传"+mm+"的首页数据，请先上传首页数据。";
                message = errorInfoString;
                //暂停50毫秒
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
                message="已中断";
                return InvokeResult.failure(message);
            }


            //读取表单数据
            for (int numRows = 1; numRows <= rowTempMe ; numRows++) {
                row = sheet.getRow(numRows);
                Medins medins = new Medins();
                errorRow = String.valueOf(numRows);
                System.out.print("123456======="+row.getCell(1));
                if(null == row.getCell(1)){//排除空行
                    System.out.print("000000000000======="+row.getCell(1));
                    continue;
                }
                GlobalData.percent=(float)numRows*100/(float)rowTempMe;
                for (int numCells = 0; numCells < row.getLastCellNum(); numCells++) {
                    cell = row.getCell((short) numCells);
                    String aaString=title[numCells];
                    errorCell = String.valueOf(numCells);

                    switch (aaString) {
                        case "病案号":
                            if(cell==null){
                                medins.setMrNo("");
                                mrNotemp2 = "";
                            }else{
                                row.getCell(numCells).setCellType(Cell.CELL_TYPE_STRING);
                                mrNotemp2 = row.getCell(numCells).getStringCellValue();

                                //不足十位的前面补0（因为首页结构化存储传过来的病案号是这样）
                                if (mrNotemp2 != null && isAnzhen){
                                    mrNotemp2 = zero[10-mrNotemp2.length()] + mrNotemp2;
                                }

                                medins.setMrNo(mrNotemp2);
                            }
                            break;
                        case "出院日期":
                            if(cell==null){
                                medins.setOutDate(null);
                                outDateMedins = null;
                            }else{
                                medins.setOutDate(cell.getDateCellValue());
                                outDatetemp2 = cell.getDateCellValue();
                                outDateMedins =outDatetemp3.format(outDatetemp2);
                            }
                            break;
                        case "入院日期":
                            if(cell==null){
                                medins.setInDate(null);
                                inDateMedins = null;
                            }else{
                                medins.setInDate(cell.getDateCellValue());
                                inDatetemp2 = cell.getDateCellValue();
                                inDateMedins =inDatetemp3.format(inDatetemp2);
                            }
                            break;
                        case "红冲标识":
                            if(cell==null){
                                medins.setRedMark("");
                            }else{
                                cell.setCellType(Cell.CELL_TYPE_STRING);
                                medins.setRedMark(cell.getStringCellValue());
                            }
                            break;
                        case "基金支付":
                            if(cell==null){
                                medins.setFundPay(0.0);
                            }else{
                                medins.setFundPay(cell.getNumericCellValue());
                            }
                            break;
                        case "自费费用":
                            if(cell==null){
                                medins.setPrivatePay(0.0);
                            }else{
                                medins.setPrivatePay(cell.getNumericCellValue());
                            }
                            break;
                        case "个人自付一":
                            if(cell==null){
                                medins.setPrivatePay1(0.0);
                            }else{
                                medins.setPrivatePay1(cell.getNumericCellValue());
                            }
                            break;
                        case "个人自付二":
                            if(cell==null){
                                medins.setPrivatePay2(0.0);
                            }else{
                                medins.setPrivatePay2(cell.getNumericCellValue());
                            }
                            break;
                        case "医疗类别":
                            if(cell==null){
                                medins.setMedicalCategory(null);
                            }else{
                                medins.setMedicalCategory(cell.getStringCellValue());
                            }
                            break;
                        case "出院类型":
                            if(cell==null){
                                medins.setOutType(null);
                            }else{
                                medins.setOutType(cell.getStringCellValue());
                            }
                            break;
                        case "医保类型":
                            if(cell==null){
                                medins.setHiType("");
                            }else{
                                String hiType="";
                                if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                                    hiType=cell.getStringCellValue();

                                } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                                    row.getCell(numCells).setCellType(Cell.CELL_TYPE_STRING);
                                    hiType=row.getCell(numCells).getStringCellValue();
                                }
                                //只存储医保类型（code），不存基金类型
                                Map<String,String> mapDi=drgsServiceApplication.findMedinsType(hiType);
                                medins.setHiType(mapDi.get("code").toString());
                            }
                            break;
                        case "险种类型":
                            if(cell==null){
                                medins.setHiType("");
                            }else{
                                String hiType="";
                                if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                                    hiType=cell.getStringCellValue();

                                } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                                    row.getCell(numCells).setCellType(Cell.CELL_TYPE_STRING);
                                    hiType=row.getCell(numCells).getStringCellValue();
                                }
                                //只存储医保类型（code），不存基金类型
                                try {
                                    Map<String,String>  mapDi=drgsServiceApplication.findMedinsType(hiType);
                                    medins.setHiType(mapDi.get("code").toString());
                                } catch (Exception e){
                                    e.printStackTrace();
                                }

                            }
                            break;
                        case "拒付总金额":
                            if(cell==null){
                                medins.setRefuseFee(0.0);
                            }else{
                                medins.setRefuseFee(cell.getNumericCellValue());
                            }
                            break;
                        case "拒付原因":
                            if(cell==null){
                                medins.setRefuseReason("");
                            }else{
                                medins.setRefuseReason(cell.getStringCellValue());
                            }
                            break;
                    }
                }
                System.out.println("========================mrNotemp2"+mrNotemp2);
                //查找当前病案号和出院日期的医保数据在首页表中是否存在
                mrIDList = medicalRecordApplication.findMrIdByMrNoAndOutDate(mrNotemp2,"",outDateMedins);
                List<String> listMark = new ArrayList<String>();// 存放红冲过滤集合
                String remarkStr=GlobalData.sysConfig.get("RED_MARK");
                if(remarkStr!=null){
                    String[] redMarkFlag = remarkStr.split("&");
                    for (String mark : redMarkFlag) {
                        listMark.add(mark);// 压入前台配置的红冲过滤类型
                    }
                }
                if(!listMark.contains(medins.getRedMark()) && (!"急诊留观".equals(medins.getMedicalCategory()) || ("急诊留观".equals(medins.getMedicalCategory()) && "转出院".equals(medins.getOutType())))){
                    //红冲为正常类型，不为急诊留观病例，或为急诊留观病例且出院方式为转出院，则为有效数据，其他为垃圾数据，不处理
                    if(mrIDList!=null && mrIDList.size()>0){//当前医保数据在首页表中有对应信息
                        if(mrIDList.size()==1)
                        {//一一对应
                            medins.setParid(mrIDList.get(0));
                        }
                        else
                        {//当前医保数据在首页表中有多次出院信息  记录下来
                            listOutDateErr.add(mrNotemp2+"-"+outDateMedins);
                        }
                    }else{//当前医保数据在首页表中没有对应信息
                        listOutDateErr.add(mrNotemp2+"-"+outDateMedins);
                        //病案号+入院日期
                        mrIDList = medicalRecordApplication.findMrIdByMrNoAndOutDate(mrNotemp2,inDateMedins,"");
                        if(mrIDList!=null && mrIDList.size()>0)
                        {//当前医保数据在首页表中有对应信息
                            if(mrIDList.size()==1)
                            {//一一对应
                                medins.setParid(mrIDList.get(0));
                            }
                            else
                            {//当前医保数据在首页表中有多次入院信息  记录下来
                                listOutDateErr.add(mrNotemp2+"-"+inDateMedins);
                            }
                        }
                    }
                }

                System.out.println("========================行数"+sheet.getLastRowNum());
                if(null != medins.getParid() && !"".equals(medins.getParid())){
                    //medinses.add(medins);
                    if ("中途结算".equals(medins.getOutType())&&!listMark.contains(medins.getRedMark())){//判断是否是红冲标示为正常但是中途结算病人
                        list0.add(mrNotemp2+"-"+outDateMedins);
                    }else if (!"急诊留观".equals(medins.getMedicalCategory()) && !listMark.contains(medins.getRedMark()) ) {//筛选红冲正常的非急诊留观病人
                        medinsOutdateMap.put(mrNotemp2+"-"+outDateMedins, medins);//构建医保表map，key是并好好+出院日期
                    }else if ("急诊留观".equals(medins.getMedicalCategory()) && "转出院".equals(medins.getOutType()) && !listMark.contains(medins.getRedMark()) ) {//筛选红冲正常的非急诊留观病人
                        medinsOutdateMap.put(mrNotemp2+"-"+outDateMedins, medins);//构建医保表map，key是并好好+出院日期
                    }
                }
            }

        }catch (Exception e) {
            e.printStackTrace();
            String errorInfoString = "表"+filePath+"的第"+errorRow+"行 "+"第"+errorCell+"列数据有问题，请检查后重新提交";
            message = errorInfoString;
            System.out.println("==========="+errorInfoString);
            //暂停250毫秒
            try {
                Thread.sleep(250);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            message="已中断";
            return InvokeResult.failure(message);

        }
        finally {

            File tempFile = new File(filePath);
            if(tempFile.isFile() || tempFile.list().length ==0)  {
                System.out.println("============删除tempFile1=============");
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                tempFile.delete();
            }
        }
        //检查id
        try{
            //中途结算不为空
            if(listOutDateErr.size()==0){//可以直接保存
                int cnt = 1;//记录当前处理的是第几个对象
                for(Object o:medinsOutdateMap.keySet()){
                    printProgress(medinsOutdateMap.size(), cnt);
                    cnt ++;
                    medinsOutdateMap.get(o).setIsAbnormal("0");//能插入成功的代表不是异常数据
                    medinsApplication.creatMedins(medinsOutdateMap.get(o));	//过滤红冲标志
                }
                String rnInfo = "成功导入医保数据"+cnt+"条<br/>";
                if(list0.size()>0){
                    rnInfo = rnInfo + "以下是未入库的中途结算id,请记录:<br/>";
                    for (int j = 0; j < list0.size(); j++) {
                        rnInfo=rnInfo+list0.get(j)+"  ";
                    }
                }
                message = rnInfo;
            }
            else{
                String rnInfo = "下列数据为医保表中的住院病人,但首页表中没有该数据,可能由于入院日期、出院日期问题,请进行检查修改:<br/>";
                for(int i = 0;i<listOutDateErr.size();i++){
                    rnInfo = rnInfo + listOutDateErr.get(i) + "  ";
                }
                rnInfo = rnInfo + "<br/>";
                if(list0.size()>0){
                    rnInfo = rnInfo + "以下是未入库的中途结算id,请记录:<br/>";
                    for (int j = 0; j < list0.size(); j++) {
                        rnInfo=rnInfo+list0.get(j) + "  ";
                    }
                }
                message = rnInfo;

                //等待操作结果
                try {
                    Thread.sleep(3500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                message = "pause";
                while(true){
                    if("1".equals(GlobalData.cookie.get(user_guid))){
                        break;
                    }
                }
                int mdeNum=1;
                if("continue".equals(GlobalData.cookie.get(user_guid+"_operation"))){
                    for(Object o:medinsOutdateMap.keySet()){
                        printProgress(medinsOutdateMap.size(), mdeNum);
                        medinsApplication.creatMedins(medinsOutdateMap.get(o));
                        mdeNum++;
                    }
                    message =  "成功导入医保数据"+(mdeNum-1)+"条";
                    InvokeResult.failure("成功导入医保数据"+(mdeNum-1)+"条");

                }
                InvokeResult.failure("取消操作");
            }

        }catch (Exception e) {
            e.printStackTrace();
            System.out.println("===========我是医保对比数据时报的错，我还没有被处理================");
        }
        if(cur==all){
            finish("已完成");
        } else  {
            message="";
            GlobalData.percent=0;
            detail="";
        }
        return InvokeResult.success();
    }
	
	int totalNum = 0;
	int currNum = 0;


	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.FileUploadFacade#getNoDataDay()
	 */
	@Override
	public InvokeResult getNoDataDay(String hospCode) {
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
    	Calendar calendar=Calendar.getInstance();
    	Calendar cal=Calendar.getInstance();
		calendar.add(Calendar.DATE, -1);
		cal.add(Calendar.MONTH, -2);//计算上2个月
		cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));//上个月的第一天
		String yesterday=dateFormat.format(calendar.getTime());//昨天日期
		String lastMonth=dateFormat.format(cal.getTime());


		List<String> dayAllList=new ArrayList<String>();//存储全日期List
		int count=0;
		List<String> daysList=new ArrayList<String>();//存储当前数据库中已有的日期List
	   	//构建全日期的List 
		while(calendar.compareTo(cal)>=0)
		  {
			dayAllList.add(dateFormat.format(cal.getTime()));
			System.out.println(cal.getTime());
			cal.add(Calendar.DATE, 1);
		   count++;
		  }
		
		System.out.println("yesterday:"+yesterday+"----上个月："+lastMonth+"---------昨天-上个月");
		System.out.println("count:"+count+"dateList.size:"+dayAllList.size());
		
	   	List<String> haveDataDayList= dailyRecordApplication.haveDataDayList(yesterday,lastMonth,hospCode);
	  	if (!haveDataDayList.isEmpty()) {
			for (String havedate:haveDataDayList) {
				daysList.add(havedate);
			}
		}
			
		System.out.println("daysList.si:"+daysList.size()+"dateList.size:"+dayAllList.size());
		//计算交集的差集
		List<String> tempDayAll = new ArrayList<String>();//excelDrg,drgList
		tempDayAll.addAll(dayAllList);
		tempDayAll.retainAll(daysList);//day对比交集大小
		dayAllList.removeAll(tempDayAll);//交集的差集，差集为0，说明drg全能对上
		
		System.out.println("daysList.si:"+daysList.size()+"dayAllList.size:"+dayAllList.size());
		return InvokeResult.success(dayAllList);
	}
	
	/**
	 * @methodname    :getProgress
	 * @description   :获取执行进度
	 * @param         :
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年1月27日
	 */
	@Override
	public void getProgress(HttpServletResponse response){
		DecimalFormat df = new DecimalFormat("##0.00");
		response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer=null;
        do {
        	//循环输出进度信息
	    	try {
	    		writer=response.getWriter();
	    		writer.write("data: {\"msg\":\""+message+"\",\"percent\":\""+df.format(GlobalData.percent)+"\",\"detail\":\""+detail+"\",\"time\":\""+time+"\"}\n\n");
				writer.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
	    	
	    	if (GlobalData.percent==100) {
	    		break;//进度为100是退出循环
			}
	    	
	    	//暂停20毫秒
	    	try {
				Thread.sleep(20);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
        } while (GlobalData.percent<=100);//进度为100是退出循环
        writer.close();
		System.out.println("进度信息调用完毕");
	}
	
	@Override
	public Map<String,Object> requestProgress() {
		/**
         * fileInfo-正在处理的文件
         * saveInfo-保存信息
         * dataInfo-数据信息
         * errorInfo-错误信息
         * stateInfo-状态
         * percent-百分比
         */
		DecimalFormat df = new DecimalFormat("##0.00");
		Map<String,Object> processInfo = new HashMap<String,Object>();
		processInfo.put("fileInfo",GlobalData.fileInfo);
		processInfo.put("saveInfo",GlobalData.saveInfo);
		processInfo.put("dataInfo",GlobalData.dataInfo);
		processInfo.put("percent",df.format(GlobalData.percent));
		processInfo.put("errorInfo",GlobalData.errorInfo);
		processInfo.put("stateInfo",GlobalData.stateInfo);
		return processInfo;
	}
	
	/**
	 * @methodname    :printProgress
	 * @description   :打印循环的进度
	 * @param         :total：总数，i：当前位置
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年1月26日
	 */
	private void printProgress(int total,int i) {
		GlobalData.percent=(float)i*100/(float)total;
		if(i>=total)
		{GlobalData.percent=100;}
		long perTime = i>0?((new Date().getTime()-mdStartTime)/i):9999;//平均时间
		time = ms2desc((total-i)*perTime);//剩余时间
	}
	
	/**
	 * @methodname    :ms2desc
	 * @description   :毫秒转时间描述
	 * @param         :
	 * @author        :WangTeng
	 * @return        :
	 * @date          :2015年5月29日
	 */
	public static String ms2desc(long ms){
		long hour=ms/(1000*60*60);
		long minute=(ms%(1000*60*60))/(1000*60);
		long second=(ms%(1000*60))/(1000);
		String desc = "";
		if (hour>0) {
			desc+=hour+"小时";
		}
		if (minute>0) {
			desc+=minute+"分";
		}
		
		if (second>0) {
			desc+=second+"秒";
		}
		return desc;
	}
	
	@Override
	public InvokeResult judgeManage(ManageSummaryDTO dto) {
		int c = quotaManageApplication.judgeManage(ManageSummaryAssembler.toEntity(dto));
		return InvokeResult.success(c); 
	}
	
	@Override
	public InvokeResult getProcess() {
		double per = Arith.div(cur, all , 4)*100;
		if(cur == all){
			per=100;
		}
		return InvokeResult.success(per);
	}
	
	
	/**
	 * 
	 *  initFieldMapInfo.  
	 *  @Description：初始化字段映射信息
	 *  @Author mazhaoyan
	 *  @param fileType 文件类型
	 *  @Date:2018年1月21日下午9:32:53
	 */
	private void initFieldMapInfo() {
		//清空
		keyFieldMap.clear();
		baseInfoFieldMap.clear();
		ipInfoFieldMap.clear();
		appendInfoFieldMap.clear();
		mainDiagFieldMap.clear();
		otherDiagMap.clear();
		mainOperFieldMap.clear();
		otherOperMap.clear();
		expInfoFieldMap.clear();
		//获取主键相关字段
		keyFieldMap = fieldMapApplication.getKeyMap("otherFile");
		//从数据库中获取 映射关系
        //获取基本信息
        baseInfoFieldMap = fieldMapApplication.getFieldMap("otherFile","MR_BASEINFO");            
        //获取住院信息
        ipInfoFieldMap = fieldMapApplication.getFieldMap("otherFile","MR_IPINFO");
        //附页信息
        appendInfoFieldMap = fieldMapApplication.getFieldMap("otherFile","MR_APPENDPAGE");
        List<Map<String,Object>> diagFieldMap = fieldMapApplication.getFieldMap("otherFile","MR_DIAGNOSE");//诊断信息字段映射关系
        for(int i = 0;i<diagFieldMap.size();i++){
			String order = diagFieldMap.get(i).get("FIELD_ORDER").toString();
			String type = diagFieldMap.get(i).get("FIELD_TYPE").toString();
			if("M".equals(type)){
				mainDiagFieldMap.add(diagFieldMap.get(i));
			}else{
				if(otherDiagMap.get(order)==null){//当前序号的还没有存
					List<Map<String,Object>> ol = new LinkedList<Map<String,Object>>();
					ol.add(diagFieldMap.get(i));
					otherDiagMap.put(order,ol);
				}else{//当前顺序存在
					otherDiagMap.get(order).add(diagFieldMap.get(i));
				}
			}
			
		}
        List<Map<String,Object>> operFieldMap = fieldMapApplication.getFieldMap("otherFile","MR_OPERATION");//手术信息字段映射关系
        for(int i = 0;i<operFieldMap.size();i++){
			String order = operFieldMap.get(i).get("FIELD_ORDER").toString();
			String type = operFieldMap.get(i).get("FIELD_TYPE").toString();
			if("M".equals(type)){
				mainOperFieldMap.add(operFieldMap.get(i));
			}else{
				if(otherOperMap.get(order)==null){//当前序号的还没有存
					List<Map<String,Object>> ol = new LinkedList<Map<String,Object>>();
					ol.add(operFieldMap.get(i));
					otherOperMap.put(order,ol);
				}else{//当前顺序存在
					otherOperMap.get(order).add(operFieldMap.get(i));
				}
			}
		}
        //获取费用信息
        expInfoFieldMap = fieldMapApplication.getFieldMap("otherFile","MR_EXPENSE");
	}
	/**
	 * 
	 *  parseRowData.  
	 *  @Description：处理行数据
	 *  @Author mazhaoyan
	 *  @param rowData
	 *  @throws Exception 
	 *  @Date:2018年1月21日下午9:40:53
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Map<String,Object> parseRowData(Object[] rowData,Map<String,Object>initMap){
		Map<String,Object> caseMap = new HashMap<String,Object>();//病例信息map
		Map<String,String> dataTypeMap = (Map<String, String>) initMap.get("dataTypeMap");
		String pMainIndex = UUID.randomUUID().toString();// 基本信息表主键
		String mrNo = "";// 病案号
		String mrOutDate = "";// 出院日期
		String mrInHospCount = "";// 住院次数
		// 基本信息
		MrBaseInfo mrBaseInfo = new MrBaseInfo();
		// 住院信息
		MrIpInfo mrIpInfo = new MrIpInfo();
		// 附页基本信息
		MrAppendPage mrAppendInfo = new MrAppendPage();
		//诊断list
		List<MrDiagnose> diagList = new ArrayList<MrDiagnose>();
		//手术list
    	List<MrOperation> operList = new ArrayList<MrOperation>();
    	//费用list
    	List<MrExpense> expList = new ArrayList<MrExpense>();
    	String titleName = "";
    	String fieldCode = "";
    	String errInfo = "";//错误信息
    	String fieldErr = "";//字段错误
		try {
			//先获取主键相关字段
			for(int i = 0;i<keyFieldMap.size();i++){
				titleName = keyFieldMap.get(i).get("TITLE_NAME").toString();
				fieldCode = keyFieldMap.get(i).get("FIELD_CODE").toString();
				int position =  fieldMap.get(titleName);
				String fieldValue = rowData[position].toString();
				if(StringUtils.hasLength(fieldValue)){
					if("P00050000".equals(fieldCode)){
						//病案号
						mrNo = rowData[position].toString();
					}
					else if("P00040000".equals(fieldCode))
					{//住院次数
						mrInHospCount = rowData[position].toString();
					}
					else if("P00290000".equals(fieldCode))
					{//出院日期
						Date date = DrgsIndex.parseDateStr(rowData[position].toString());
						if(date!=null)
						{
							mrOutDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
						}
					}
				}
	    	}
			//处理基本信息
	    	for(int i = 0;i<baseInfoFieldMap.size();i++){
	    		titleName = baseInfoFieldMap.get(i).get("TITLE_NAME").toString();
	    		fieldCode = baseInfoFieldMap.get(i).get("FIELD_CODE").toString();
	    		Integer position =  fieldMap.get(titleName);
	    		if(position!=null && rowData[position]!=null){
	    			fieldErr = DrgsIndex.setElementValueFileUpload(mrBaseInfo,fieldCode,rowData[position].toString(),dataTypeMap.get(fieldCode),null);
	    			if(StringUtils.hasLength(fieldErr)){
	    				errInfo += "MR_BASEINFO "+ fieldCode + " " + fieldErr+"\n";
	    			}
	    		}
	    	}
	    	baseDictMap(mrBaseInfo,(Map<String,Object>)initMap.get("dictData"));//字典匹配
	    	
			//处理住院信息
	    	for(int i = 0;i<ipInfoFieldMap.size();i++){
	    		titleName = ipInfoFieldMap.get(i).get("TITLE_NAME").toString();
	    		fieldCode = ipInfoFieldMap.get(i).get("FIELD_CODE").toString();
	    		Integer position =  fieldMap.get(titleName);
	    		if(position!=null && rowData[position]!=null){
	    			fieldErr = DrgsIndex.setElementValueFileUpload(mrIpInfo,fieldCode,rowData[position].toString(),dataTypeMap.get(fieldCode),null);
	    			if(StringUtils.hasLength(fieldErr)){
	    				errInfo += "MR_IPINFO "+ fieldCode + " " + fieldErr+"\n";
	    			}
	    		}
	    	}
	    	ipDictMap(mrIpInfo,(Map<String,Object>)initMap.get("dictData"));//字典匹配
	    	
			titleName = "处理科室病区医师 ";
			synchronized(initMap){
				parseDepDoc(mrBaseInfo,mrIpInfo,initMap);//处理科室病区医师
			}
			
			//PMAININDEX
			if(StringUtils.hasLength(mrBaseInfo.getPmainIndex())){
				pMainIndex = mrBaseInfo.getPmainIndex();
			} else {
				pMainIndex = mrNo + "-" + mrOutDate + "-" + mrInHospCount;
			}
			
	    	//处理附页信息
	    	for(int i = 0;i<appendInfoFieldMap.size();i++){
	    		titleName = appendInfoFieldMap.get(i).get("TITLE_NAME").toString();
	    		fieldCode = appendInfoFieldMap.get(i).get("FIELD_CODE").toString();
	    		Integer position =  fieldMap.get(titleName);
	    		if(position!=null && rowData[position]!=null){
	    			fieldErr = DrgsIndex.setElementValueFileUpload(mrAppendInfo,fieldCode,rowData[position].toString(),dataTypeMap.get(fieldCode),null);
	    			if(StringUtils.hasLength(fieldErr)){
	    				errInfo += "MR_APPENDINFO "+ fieldCode + " " + fieldErr+"\n";
	    			}
	    		}
    		}
	    	//处理主要诊断信息
	    	int diagIndex = 0;
	    	MrDiagnose mrDiagMain = new MrDiagnose();
			for(int i = 0;i<mainDiagFieldMap.size();i++){
	    		titleName = mainDiagFieldMap.get(i).get("TITLE_NAME").toString();
	    		fieldCode = mainDiagFieldMap.get(i).get("FIELD_CODE").toString();
	    		Integer position =  fieldMap.get(titleName);
	    		if(position!=null && rowData[position]!=null){
	    			fieldErr = DrgsIndex.setElementValueFileUpload(mrDiagMain,fieldCode,rowData[position].toString(),dataTypeMap.get(fieldCode),null);
	    			if(StringUtils.hasLength(fieldErr)){
	    				errInfo += "MAIN MR_DIAGNOSE "+ fieldCode + " " + fieldErr+"\n";
	    			}
	    		}
	    	}
			if(!DrgsIndex.isAllFieldNull(mrDiagMain))
			{//诊断编码不为空 保存
				mrDiagMain.setId(UUID.randomUUID().toString());
				mrDiagMain.setPmainIndex(pMainIndex);
				mrDiagMain.setPdType("M");
				mrDiagMain.setPdIndex(diagIndex++);
				diagList.add(mrDiagMain);
			}
	    	//处理其他诊断信息
	    	for (String key : otherDiagMap.keySet()) {
				List<Map<String, Object>> ol = otherDiagMap.get(key);
				// 诊断信息
				MrDiagnose mrDiagOther = new MrDiagnose();
				// 循环其它诊断具体的节点，取值并保存
				for (Map<String, Object> map : ol) {
					titleName = map.get("TITLE_NAME").toString();
					fieldCode = map.get("FIELD_CODE").toString();
	        		Integer position =  fieldMap.get(titleName);
	        		if(position!=null && rowData[position]!=null){
	        			fieldErr = DrgsIndex.setElementValueFileUpload(mrDiagOther,fieldCode,rowData[position].toString(),dataTypeMap.get(fieldCode),null);
		    			if(StringUtils.hasLength(fieldErr)){
		    				errInfo += "other "+key+" MR_DIAGNOSE "+ fieldCode + " " + fieldErr+"\n";
		    			}
	        		}
	        	}
				if(!DrgsIndex.isAllFieldNull(mrDiagOther)){
					//诊断编码不为空 保存
					mrDiagOther.setId(UUID.randomUUID().toString());
					mrDiagOther.setPmainIndex(pMainIndex);
					mrDiagOther.setPdType("O");
					mrDiagOther.setPdIndex(diagIndex++);
					diagList.add(mrDiagOther);
				}
			}
	    	//处理主要手术信息
	    	int operIndex = 0;
			MrOperation mr_oper_main = new MrOperation();
			for(int i = 0;i<mainOperFieldMap.size();i++)
	    	{
	    		titleName = mainOperFieldMap.get(i).get("TITLE_NAME").toString();
	    		fieldCode = mainOperFieldMap.get(i).get("FIELD_CODE").toString();
	    		Integer position =  fieldMap.get(titleName);
	    		if(position!=null && rowData[position]!=null){
	    			fieldErr = DrgsIndex.setElementValueFileUpload(mr_oper_main,fieldCode,rowData[position].toString(),dataTypeMap.get(fieldCode),null);
	    			if(StringUtils.hasLength(fieldErr)){
	    				errInfo += "main MR_OPERATION "+ fieldCode + " " + fieldErr+"\n";
	    			}
	    		}
	    	}
			if(!DrgsIndex.isAllFieldNull(mr_oper_main))
			{//手术编码不为空 保存
				mr_oper_main.setId(UUID.randomUUID().toString());
				mr_oper_main.setPmainIndex(pMainIndex);// 病例外键
				mr_oper_main.setPoType("M");
				if(mr_oper_main.getPo1400()==null)
				{
					mr_oper_main.setPo1400("1");
				}
				synchronized (initMap) {
					parseOperDoc(initMap,mr_oper_main);
				}
				operDictMap(mr_oper_main,(Map<String,Object>)initMap.get("dictData"));
				mr_oper_main.setPoIndex(operIndex++);
				operList.add(mr_oper_main);
			}
	    	
	    	//处理其他手术信息
	    	for (String key : otherOperMap.keySet()) {
				List<Map<String, Object>> ol = otherOperMap.get(key);
				// 手术信息
				MrOperation mr_oper_other = new MrOperation();
				// 循环其它手术具体的节点，取值并保存
				for (Map<String, Object> map : ol) {
					titleName = map.get("TITLE_NAME").toString();
					fieldCode = map.get("FIELD_CODE").toString();
	        		Integer position =  fieldMap.get(titleName);
	        		if(position!=null && rowData[position]!=null){
	        			fieldErr = DrgsIndex.setElementValueFileUpload(mr_oper_other,fieldCode,rowData[position].toString(),dataTypeMap.get(fieldCode),null);
		    			if(StringUtils.hasLength(fieldErr)){
		    				errInfo += "other "+key+" MR_OPERATION "+ fieldCode + " " + fieldErr+"\n";
		    			}
	        		}
				}
				if(!DrgsIndex.isAllFieldNull(mr_oper_other))
				{//手术编码不为空时 才进行存储
					mr_oper_other.setId(UUID.randomUUID().toString());
					mr_oper_other.setPmainIndex(pMainIndex);// 病例外键
					mr_oper_other.setPoType("O");
					if(mr_oper_other.getPo1400()==null)
					{
						mr_oper_other.setPo1400("1");
					}
					synchronized (initMap) {
						parseOperDoc(initMap,mr_oper_other);
					}
					operDictMap(mr_oper_other,(Map<String,Object>)initMap.get("dictData"));
					mr_oper_other.setPoIndex(operIndex++);
					operList.add(mr_oper_other);
				}
			}
	    	//处理费用信息
			int expIndex = 0;
	    	for(int i = 0;i<expInfoFieldMap.size();i++)
	    	{
	    		titleName = expInfoFieldMap.get(i).get("TITLE_NAME").toString();
	    		fieldCode = expInfoFieldMap.get(i).get("FIELD_CODE").toString();// 费用编码
	    		Integer position =  fieldMap.get(titleName);
	    		if(position!=null && rowData[position]!=null)
	    		{
	    			String value = rowData[position].toString();
	    			if(value.matches("^(\\-|\\+)?(\\d+\\.\\d+|\\d+|\\.\\d+)$"))
	    			{
	    				double tmpC = Double.parseDouble(value);
						MrExpense mr_expense = new MrExpense();
						mr_expense.setId(UUID.randomUUID().toString());
						mr_expense.setPe0101(fieldCode);// 费用代码
						mr_expense.setPe0200(tmpC);// 费用值
						mr_expense.setPeIndex(expIndex++);//序号码
						mr_expense.setPmainIndex(pMainIndex);// 病例外键
						expList.add(mr_expense);
	    			}
	    		}
	    	}
	    	
	    	mrBaseInfo.setPmainIndex(pMainIndex);
			mrIpInfo.setPmainIndex(pMainIndex);
			mrAppendInfo.setPmainIndex(pMainIndex);

            //计算新生儿天数(月/天)
            if(mrBaseInfo.getP00080000()!=null && mrIpInfo.getP00250000()!=null){
                //计算天数
                int days = (int) ((mrIpInfo.getP00250000().getTime() - mrBaseInfo.getP00080000().getTime()) / (1000*3600*24));
                if(days < 365){
                    if(days < 1){
                        mrBaseInfo.setP00090002(1);
                    } else if (days < 30){
                        mrBaseInfo.setP00090002(days);
                    } else {
                        mrBaseInfo.setP00090001(days/30); //取余
                        mrBaseInfo.setP00090002(days%30); //取模
                    }
                    mrBaseInfo.setP00090000(0);
                }
            }
			
			//返回数据
			caseMap.put("pMainIndex",pMainIndex);
			caseMap.put("base",mrBaseInfo);
			caseMap.put("ip",mrIpInfo);
			caseMap.put("append",mrAppendInfo);
			caseMap.put("diag",diagList);
			caseMap.put("oper",operList);
			caseMap.put("exp",expList);
		} catch (Exception e) {
			errInfo += titleName+ " " +e.getMessage();
		}finally {
			if(StringUtils.hasLength(errInfo)){
				caseMap = null;//病例有问题 数据置空
				//写入log日志
				logger.error(errInfo);
			}
		}
		return caseMap;
	}
	
	/**  
	 *  getDictData.  
	 *  @Description：获取字典映射值
	 *  @Author mazhaoyan
	 *  @param initMap
	 *  @param string
	 *  @param string2 
	 *  @Date:2018年4月2日下午2:49:37   
	 */
	@SuppressWarnings("unchecked")
	public String getDictData(Map<String,Object> dictMap, String key, String value) {
		String code = null;
		if(dictMap!=null&&dictMap.get(key+"#"+value)!=null)
		{
			code = dictMap.get(key+"#"+value).toString();
		}
		return code;
	}
	/**
	 * 
	 *  assembleGroupData.  
	 *  @Description：组装分组用数据
	 *  @Author mazhaoyan
	 *  @param baseInfo
	 *  @param ipInfo
	 *  @param appendInfo
	 *  @param tmpDiagList
	 *  @param tmpOperList
	 *  @return 
	 *  @Date:2018年1月20日上午9:43:45
	 */
	@Override
	public void assembleAndGroup(MrBaseInfo baseInfo, MrIpInfo ipInfo, MrAppendPage appendInfo, List<MrDiagnose> tmpDiagList, List<MrOperation> tmpOperList, Map<String, Object> initMap) {
		Map<String, Object> resultMap=new HashMap<>();
		String groupVerCode = initMap.get("groupVerCode").toString();
    	String groupVer = initMap.get("groupVer").toString();
    	String isICDMatch = initMap.get("isICDMatch").toString();
    	String groupAddr = initMap.get("groupAddr").toString();
    	String icdOperVer = initMap.get("icdOperVer").toString();
    	boolean groupAgain="1".equals(initMap.get("groupAgain").toString());
    	String verRegion = initMap.get("verRegion").toString();
		Map<String,Object> patientMap = new HashMap<String,Object>();
		List<String> diags = new ArrayList<>();
		List<String> opers = new ArrayList<>();
		patientMap.put("ver", groupVer);
		patientMap.put("CASE_ID", baseInfo.getPmainIndex());
		String gender = baseInfo.getP00070001();
		if (gender!=null&&gender.equals("1")) {
			patientMap.put("GENDER", "男");
		} else if (gender!=null&&gender.equals("2")) {
			patientMap.put("GENDER", "女");
		} else {
			patientMap.put("GENDER", gender);
		}
		patientMap.put("AGE", baseInfo.getP00090000());
		patientMap.put("TOTAL_EXPENSE", ipInfo.getP00800000());
		patientMap.put("ACCTUAL_DAYS", ipInfo.getP00320000());
		patientMap.put("SF0108", ipInfo.getP00620001());//离院方式代码
		if(baseInfo.getP00090000()==null||baseInfo.getP00090000()==0)
		{//年龄为空或者为0
			if(baseInfo.getP00090001()!=null||baseInfo.getP00090002()!=null)
			{
				//新生儿年龄
				int babyAge = 0;
				if(baseInfo.getP00090001()!=null)
				{
					babyAge +=baseInfo.getP00090001()*30;
				}
				if(baseInfo.getP00090002()!=null)
				{
					babyAge +=baseInfo.getP00090002();
				}
				if(babyAge==0)
				{
					babyAge = 1;//当新生儿年龄为0时 +1 否则不入组
				}
				patientMap.put("SF0100", babyAge);//新生儿年龄
			}
		}
		patientMap.put("SF0102", baseInfo.getP00120000());//新生儿体重
		patientMap.put("SF0104", appendInfo.getP90120201());//呼吸机使用时间
		//诊断
		for(int i=0;i<tmpDiagList.size();i++){
			if("M".equals(tmpDiagList.get(i).getPdType())){
				patientMap.put("DISEASE_CODE",tmpDiagList.get(0).getPd0101());//主要诊断
			}else {
				diags.add(tmpDiagList.get(i).getPd0101());
			}
		}
		for(int i=0;i<tmpOperList.size();i++)
		{//手术
			opers.add(tmpOperList.get(i).getPo0101());
		}
		if (diags.size()>0) {
			patientMap.put("DIAGS_CODE", diags);
		}
		if (opers.size()>0) {
			patientMap.put("OPERS_CODE", opers);
		}
		//分组器版本号
		String groupVersion = GlobalData.sysConfig.get("GROUP_VER");
		String icdVerCode=drgCommonApplication.getIcdVerCodeByGroupVersion(groupVersion);
		String [] icd=icdVerCode.split(",");
		//诊断编码版本
		String icdDiaVerConfig = icd[1]+"";
		//手术操作版本
		String icdOperVerConfig =icd[0]+"";
		//数据组装
		Map<String, Object> mrInfoMap=groupServiceFacade.dataGenerate(patientMap,groupVer,isICDMatch,icdDiaVerConfig,icdOperVerConfig);
		//分组
		resultMap=groupServiceFacade.group(mrInfoMap,groupAddr,groupVer,groupAgain);
		//分组结果、日志保存
		groupServiceFacade.groupResultLogSave(mrInfoMap,resultMap,groupVerCode,groupVer,verRegion,isICDMatch);
	}
	/**  
	 *  @Description：
	 *  @Author mazhaoyan  
	 *  @see com.dhcc.DRGsHosp.facade.FileUploadFacade#assembleAndGroup(java.util.Map, java.util.Map)  
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void assembleAndGroup(Map<String, Object> caseMap, Map<String, Object> initMap) {
		String autoGroup = initMap.get("autoGroup")==null?"":initMap.get("autoGroup").toString();
		MrIpInfo ipInfo = (MrIpInfo) caseMap.get("ip");
		if("true".equals(autoGroup)&&ipInfo.getP00320000()!=null&&ipInfo.getP00320000()<61){
			try {
				Map<String, Object> resultMap=new HashMap<>();
				MrBaseInfo baseInfo = (MrBaseInfo) caseMap.get("base");
				MrAppendPage appendInfo = (MrAppendPage) caseMap.get("append");
				List<MrDiagnose> tmpDiagList = (List<MrDiagnose>) caseMap.get("diag");
				List<MrOperation> tmpOperList = (List<MrOperation>) caseMap.get("oper");
				String groupVerCode = initMap.get("groupVerCode").toString();
		    	String groupVer = initMap.get("groupVer").toString();
		    	String isICDMatch = initMap.get("isICDMatch").toString();
		    	String groupAddr = initMap.get("groupAddr").toString();
		    	boolean groupAgain="1".equals(initMap.get("groupAgain").toString());
		    	String verRegion = initMap.get("verRegion").toString();
				Map<String,Object> patientMap = new HashMap<String,Object>();
				List<String> diags = new ArrayList<>();
				List<String> opers = new ArrayList<>();
				patientMap.put("ver", groupVer);
				patientMap.put("CASE_ID", baseInfo.getPmainIndex());
				String gender = baseInfo.getP00070001();
				if (gender!=null&&gender.equals("1")) {
					patientMap.put("GENDER", "男");
				} else if (gender!=null&&gender.equals("2")) {
					patientMap.put("GENDER", "女");
				} else {
					patientMap.put("GENDER", gender);
				}
				patientMap.put("AGE", baseInfo.getP00090000());
				patientMap.put("TOTAL_EXPENSE", ipInfo.getP00800000());
				patientMap.put("ACCTUAL_DAYS", ipInfo.getP00320000());
				patientMap.put("SF0108", ipInfo.getP00620001());//离院方式代码
				if(baseInfo.getP00090000()==null||baseInfo.getP00090000()==0){//年龄为空或者为0
					if(baseInfo.getP00090001()!=null||baseInfo.getP00090002()!=null){
						//新生儿年龄
						int babyAge = 0;
						if(baseInfo.getP00090001()!=null){
							babyAge +=baseInfo.getP00090001()*30;
						}
						if(baseInfo.getP00090002()!=null){
							babyAge +=baseInfo.getP00090002();
						}
						if(babyAge==0){
							babyAge = 1;//当新生儿年龄为0时 +1 否则不入组
						}
						patientMap.put("SF0100", babyAge);//新生儿年龄
					}
				}
				patientMap.put("SF0102", baseInfo.getP00120000());//新生儿体重
				patientMap.put("SF0104", appendInfo.getP90120201());//呼吸机使用时间
				//诊断
				for(int i=0;i<tmpDiagList.size();i++){
					if("M".equals(tmpDiagList.get(i).getPdType())){
						patientMap.put("DISEASE_CODE",tmpDiagList.get(0).getPd0101());//主要诊断
					}else {
						diags.add(tmpDiagList.get(i).getPd0101());
					}
				}
				for(int i=0;i<tmpOperList.size();i++){//手术
					opers.add(tmpOperList.get(i).getPo0101());
				}
				if (diags.size()>0) {
					patientMap.put("DIAGS_CODE", diags);
				}
				if (opers.size()>0) {
					patientMap.put("OPERS_CODE", opers);
				}
				String icdDiaVerConfig="";
				String icdOperVerConfig="";
				if(StringUtils.hasLength(groupVerCode)){
					//分组器版本号
					DRGVersion drgVersion=drgVersionApplication.getDRGVersion(groupVerCode);
					if(drgVersion!=null){
						//诊断编码版本
						icdDiaVerConfig = drgVersion.getIcd10Version();
						//手术操作版本
						icdOperVerConfig =drgVersion.getIcd9Version();
					}
				}
				//数据组装
				Map<String, Object> mrInfoMap=groupServiceFacade.dataGenerate(patientMap,groupVer,isICDMatch,icdDiaVerConfig,icdOperVerConfig);
				//分组
				resultMap=groupServiceFacade.group(mrInfoMap,groupAddr,groupVer,groupAgain);
				//分组结果、日志保存
				groupServiceFacade.groupResultLogSave(mrInfoMap,resultMap,groupVerCode,groupVer,verRegion,isICDMatch);
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
		}
	}
	/**  
	 *  @Description：
	 *  @Author mazhaoyan  
	 *  @see com.dhcc.DRGsHosp.facade.FileUploadFacade#baseDictMap(com.dhcc.DRGsHosp.core.domain.MrBaseInfo, java.util.Map)  
	 */
	@Override
	public void baseDictMap(MrBaseInfo mrBaseInfo, Map<String, Object> dictData) {
		if (mrBaseInfo.getP00020001() == null && mrBaseInfo.getP00020000() != null) {// 付费方式
			String payWay = mrBaseInfo.getP00020000();// 医疗付费方式
			mrBaseInfo.setP00020001(getDictData(dictData,"P00020001",payWay));
		}
		if (mrBaseInfo.getP00070001() == null && mrBaseInfo.getP00070000() != null) {// 性别
			String gender = mrBaseInfo.getP00070000();// 性别
			mrBaseInfo.setP00070001(getDictData(dictData,"P00070000",gender));
		}
	}
	/**  
	 *  @Description：
	 *  @Author mazhaoyan  
	 *  @see com.dhcc.DRGsHosp.facade.FileUploadFacade#ipDictMap(com.dhcc.DRGsHosp.core.domain.MrIpInfo, java.util.Map)  
	 */
	@Override
	public void ipDictMap(MrIpInfo mrIpInfo, Map<String, Object> dictData) {
		if (mrIpInfo.getP00230001() == null && mrIpInfo.getP00230000() != null) {// 入院途径方式
			String inWay = mrIpInfo.getP00230000();// 入院途径方式
			mrIpInfo.setP00230001(getDictData(dictData,"P00230000",inWay));
		}
		if (mrIpInfo.getP00620001() == null && mrIpInfo.getP00620000() != null) {// 离院方式
			String outWay = mrIpInfo.getP00620000();// 离院方式
			mrIpInfo.setP00620001(getDictData(dictData,"P00620000",outWay));
		}
	}

	/**  
	 *  @Description：
	 *  @Author mazhaoyan  
	 *  @see com.dhcc.DRGsHosp.facade.FileUploadFacade#operDictMap(com.dhcc.DRGsHosp.core.domain.MrOperation, java.util.Map)  
	 */
	@Override
	public void operDictMap(MrOperation mrOper, Map<String, Object> dictData) {
		if(!StringUtils.hasLength(mrOper.getPo0301())&&StringUtils.hasLength(mrOper.getPo0300())) {
		    //手术及操作i级别编码为空 手术及操作i级别不为空
			String levelDesc = mrOper.getPo0300();//手术及操作i级别
			mrOper.setPo0301(getDictData(dictData,"PO0301",levelDesc));
		}
		//麻醉方式
		if(!StringUtils.hasLength(mrOper.getPo0701())&&StringUtils.hasLength(mrOper.getPo0700())) {
		    //麻醉方式编码为空 麻醉方式不为空
			String anaesWay = mrOper.getPo0700();//麻醉方式
			mrOper.setPo0701(getDictData(dictData,"PO0301",anaesWay));
		}
		//切口愈合
		if(!StringUtils.hasLength(mrOper.getPo0801())&&StringUtils.hasLength(mrOper.getPo0800())) {
		    //切口愈合编码为空 切口愈合不为空
			String cutLev = mrOper.getPo0800();//切口愈合等级
			mrOper.setPo0801(getDictData(dictData,"PO0801",cutLev));
		}

		//手术类型
		if(StringUtils.hasLength(mrOper.getPoType()) && getDictData(dictData,"POTYPE",mrOper.getPoType())!=null) {
			mrOper.setPoType(getDictData(dictData,"POTYPE",mrOper.getPoType()));
		}
		//手术或操作
		if(StringUtils.hasLength(mrOper.getPo1400()) && getDictData(dictData,"PO1400",mrOper.getPo1400())!=null) {
			mrOper.setPo1400(getDictData(dictData,"PO1400",mrOper.getPo1400()));
		}
	}
	
	/**  
	 *  @Description：
	 *  @Author mazhaoyan  
	 *  @see com.dhcc.DRGsHosp.facade.FileUploadFacade#parseDepDoc(com.dhcc.DRGsHosp.core.domain.MrIpInfo)  
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void parseDepDoc(MrBaseInfo baseInfo,MrIpInfo ipInfo,Map<String,Object> initMap) throws Exception {
		Map<String,String> mapObj = new HashMap<>() ;
		String process ="";
		try {
			Map<String,String> resultMap = new HashMap<>() ;//医师 结果代码 名称//医师 结果代码 名称
			List<HospInfo> hospList =  (List<HospInfo>) initMap.get("hospList");//院区List
			Map<String,Object> hospCodeMap =  (Map<String, Object>) initMap.get("hospCodeMap");//医院codeMap

			// 科室组
			Map<String,Object> depGroupCodeMap = (Map<String, Object>) initMap.get("depGroupCodeMap");
			Map<String,Object> depCodeMap =  (Map<String, Object>) initMap.get("depCodeMap");
			Map<String,Object> depDescMap =  (Map<String, Object>) initMap.get("depDescMap");
			Map<String,Object> wardCodeMap =  (Map<String, Object>) initMap.get("wardCodeMap");
			Map<String,Object> wardDescMap =  (Map<String, Object>) initMap.get("wardDescMap");
			Map<String,Object> docCodeMap =  (Map<String, Object>) initMap.get("docCodeMap");
			Map<String,Object> docDescMap =  (Map<String, Object>) initMap.get("docDescMap");

            //科室去空格
            if (ipInfo.getP00260000() != null){
                ipInfo.setP00260000(ipInfo.getP00260000().replaceAll("\\s",""));
            }
            if (ipInfo.getP00270000() != null){
                ipInfo.setP00270000(ipInfo.getP00270000().replaceAll("\\s",""));
            }
            if (ipInfo.getP00300000() != null){
                ipInfo.setP00300000(ipInfo.getP00300000().replaceAll("\\s",""));
            }
            if (ipInfo.getP00310000() != null){
                ipInfo.setP00310000(ipInfo.getP00310000().replaceAll("\\s",""));
            }
            //医师去空格
            if (ipInfo.getP00600100() != null){
                ipInfo.setP00600100(ipInfo.getP00600100().replaceAll("\\s",""));
            }
            if (ipInfo.getP00600200() != null){
                ipInfo.setP00600200(ipInfo.getP00600200().replaceAll("\\s",""));
            }
            if (ipInfo.getP00600300() != null){
                ipInfo.setP00600300(ipInfo.getP00600300().replaceAll("\\s",""));
            }
            if (ipInfo.getP00600400() != null){
                ipInfo.setP00600400(ipInfo.getP00600400().replaceAll("\\s",""));
            }

			String outDepCode = ipInfo.getP00300001() ;// 出院科别编码
			String outDepDesc = ipInfo.getP00300000() ;// 出院科别
			//处理院区
			process = "处理院区代码";
			String hospCode = "";
			if(hospList.size()==1){//不区分院区
				hospCode = hospList.get(0).getHospCode();
				baseInfo.setP00010001(hospCode);//设置院区代码
			}else if(hospCodeMap.get(outDepCode)!=null){//多院区 按照科室与院区code关系获取院区code
				baseInfo.setP00010001(hospCodeMap.get(outDepCode).toString());
			}

			//出院科室处理
			process = "处理出院科室";
			mapObj.put("code",outDepCode) ;
			mapObj.put("desc",outDepDesc) ;
			mapObj.put("hospCode",hospCode) ;
			if(depGroupCodeMap.containsKey("XZKSKSZ")){
				mapObj.put("parDepGroupCode","XZKSKSZ") ;
			}
			resultMap = processCodeAndDesc(mapObj,depCodeMap,depDescMap,"dep") ;
			ipInfo.setP00300001(resultMap.get("code"));
			ipInfo.setP00300000(resultMap.get("desc"));

			process = "处理出院病区";
			//出院病房处理
			mapObj.put("code",ipInfo.getP00310001()) ;  //出院病房编码
			mapObj.put("desc",ipInfo.getP00310000()) ;  //出院病房
			mapObj.put("depCode",outDepCode) ;
			resultMap = processCodeAndDesc(mapObj,wardCodeMap,wardDescMap,"ward") ;
			ipInfo.setP00310000(resultMap.get("desc"));
			ipInfo.setP00310001(resultMap.get("code"));

			//医师处理
			process = "导入科主任";
			mapObj.put("code",ipInfo.getP00600101()) ; // 科主任编码
			mapObj.put("desc",ipInfo.getP00600100()) ; // 科主任
			resultMap = processCodeAndDesc(mapObj,docCodeMap,docDescMap,"doctor") ;
			ipInfo.setP00600100(resultMap.get("desc"));
			ipInfo.setP00600101(resultMap.get("code"));

			//主任（副主任）医师
			process = "导入主任医师";
			mapObj.put("code",ipInfo.getP00600201());  // 主任（副主任）医师编码
			mapObj.put("desc",ipInfo.getP00600200()); // 主任（副主任）医师
			resultMap = processCodeAndDesc(mapObj,docCodeMap,docDescMap,"doctor") ;
			ipInfo.setP00600200(resultMap.get("desc"));
			ipInfo.setP00600201(resultMap.get("code"));

			//主治医师
			process = "导入主治医师";
			mapObj.put("code",ipInfo.getP00600301()); // 主治医师编码
			mapObj.put("desc",ipInfo.getP00600300()); // 主治医师
			resultMap = processCodeAndDesc(mapObj,docCodeMap,docDescMap,"doctor") ;
			ipInfo.setP00600300(resultMap.get("desc"));
			ipInfo.setP00600301(resultMap.get("code"));

			//住院医师
			process = "导入住院医师";
			mapObj.put("code",ipInfo.getP00600401()); // 住院医师编码
			mapObj.put("desc",ipInfo.getP00600400()); // 住院医师
			resultMap = processCodeAndDesc(mapObj,docCodeMap,docDescMap,"doctor") ;
			ipInfo.setP00600400(resultMap.get("desc"));
			ipInfo.setP00600401(resultMap.get("code"));

			//主诊医师
			process = "导入主诊医师";
			mapObj.put("code",ipInfo.getP00601001()); // 主诊医师编码
			mapObj.put("desc",ipInfo.getP00601000()); // 主诊医师
			resultMap = processCodeAndDesc(mapObj,docCodeMap,docDescMap,"doctor") ;
			ipInfo.setP00601000(resultMap.get("desc"));
			ipInfo.setP00601001(resultMap.get("code"));


		} catch (Exception e) {
			throw  new Exception(process+" "+(e.getMessage()==null?"空指针":e.getMessage()));
		}
	}
	private void saveNewDep(String depCode,String depDesc,String hospCode) throws Exception
	{
		//把科室存到数据库里面
		Department department = new Department();
		department.setDepCode(depCode);
		department.setDepName(depDesc);
		department.setParHospCode(hospCode);//系统要内置新增科室科室组
		departmentApplication.creatDepartment(department);
	}
	private void saveNewWard(String wardCode,String wardDesc,String depCode) throws Exception
	{
		Ward ward = new Ward();
		ward.setWardCode(wardCode);
		ward.setWardDesc(wardDesc);
		ward.setDepCode(depCode==null?"unknowndep":depCode);//出院科别代码
		wardApplication.creatWard(ward);
	}
	/**
	 * 
	 *  saveNewDoc.  
	 *  @Description：保存新医师
	 *  @Author mazhaoyan
	 *  @param groupCode
	 *  @param groupName
	 *  @throws Exception 
	 *  @Date:2018年2月11日上午9:36:25
	 */
	private void saveNewDoc(String groupCode,String groupName) throws Exception
	{
		ClinicGroup doctor = new ClinicGroup();
		doctor.setId(UUID.randomUUID().toString());
		doctor.setGroupCode(groupCode);
		doctor.setGroupName(groupName);
		clinicGroupApplication.creatClinicGroup(doctor);// 保存医师
	}

	/**  
	 *  @Description：
	 *  @Author mazhaoyan  
	 *  @see com.dhcc.DRGsHosp.facade.FileUploadFacade#parseOperDoc(java.lang.String, java.lang.String)  
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void parseOperDoc(Map<String,Object> initMap,MrOperation operInfo) throws Exception {
		Map<String,String> mapObj = new HashMap<>() ;
		String process ="";
		try {
			Map<String,String> resultMap =new HashMap<>();//医师 结果代码 名称
			Map<String,Object> docCodeMap =  (Map<String, Object>) initMap.get("docCodeMap");
			Map<String,Object> docDescMap =  (Map<String, Object>) initMap.get("docDescMap");
			//导入手术术者
			process = "导入手术术者";
			mapObj.put("code",operInfo.getPo0401()); // 术者编码
			mapObj.put("desc",operInfo.getPo0400()); // 术者
			resultMap = processCodeAndDesc(mapObj,docCodeMap,docDescMap,"doctor") ;
			operInfo.setPo0400(resultMap.get("desc"));
			operInfo.setPo0401(resultMap.get("code"));

			//导入一助
			process = "导入一助";
			mapObj.put("code",operInfo.getPo0501()); // 一助编码
			mapObj.put("desc",operInfo.getPo0500()); // 一助
			resultMap = processCodeAndDesc(mapObj,docCodeMap,docDescMap,"doctor") ;

			operInfo.setPo0500(resultMap.get("desc"));
			operInfo.setPo0501(resultMap.get("code"));

			//导入二助
			process = "导入二助";
			mapObj.put("code",operInfo.getPo0601()); //二助编码
			mapObj.put("desc",operInfo.getPo0600()); // 二助
			resultMap = processCodeAndDesc(mapObj,docCodeMap,docDescMap,"doctor") ;

			operInfo.setPo0600(resultMap.get("desc"));
			operInfo.setPo0601(resultMap.get("code"));

		} catch (Exception e) {
			throw  new Exception(process+" "+(e.getMessage()==null?"空指针":e.getMessage()));
		}
	}

	@Override
	public InvokeResult costSubImport(String filePath) {
		message="";
		List<Map<String,Object>> expenseTypeList = GlobalData.sysDictionary.get("EXPENSE_TYPE") ;
		Map<String,String> mapExp = new HashMap<>() ; 
		for(Map<String,Object> expT : expenseTypeList){
			mapExp.put(StringUtils.toString(expT.get("DICDESC")), StringUtils.toString(expT.get("DICVALUE"))) ;
		}
		List<Map<String,Object>> expenseTypeFiveList = GlobalData.sysDictionary.get("EXPENSE_TYPE_FIVE") ;
		Map<String,String> mapExpF = new HashMap<>() ; 
		for(Map<String,Object> expTF : expenseTypeFiveList){
			mapExpF.put(StringUtils.toString(expTF.get("DICDESC")), StringUtils.toString(expTF.get("DICVALUE"))) ;
		}

		// 删除表中原来的数据
		costSubApplication.removeCostSubs();

		StringBuffer messageStrb = new StringBuffer();//返回前台的信息
		Sheet sheet = ExcelUtil.readExcelSheet(filePath,0);
		int rowNum=sheet.getLastRowNum();//行数
		Row row = null ;
		// 存放文件的表头位置
		Map<String,Object> titlemap = new HashMap<>();
		// 标题行
		Row headrow = sheet.getRow(0);
		int headCount = headrow.getLastCellNum();
		Cell cell=null;
		for (int i = 0; i < headCount; i++) {
			cell = headrow.getCell((short) i);
			titlemap.put(cell.getStringCellValue(), i);
		}
		int rowCnt=0;
		try {
			messageStrb.setLength(0);
			for(int i = 1 ; i <= rowNum ; i++) {
				row=sheet.getRow(i);
				// 该行为空时解析下一行
				if(ExcelUtil.isRowEmpty(row)) {
					continue ;
				}
				CostSub costSub = new CostSub() ;
				cell = row.getCell((int) (titlemap.get("编码") != null ? titlemap.get("编码"):1000));
				String costSubCode=ExcelUtil.getCellValue(cell);
				if( null == costSubCode) {
					messageStrb.append("第" + (i) +"行数据没有费用子项编码，请检查。<br>"); 
					continue ;
				}
				costSub.setCostSubcode(costSubCode) ;
				cell = row.getCell((int) (titlemap.get("描述") != null ? titlemap.get("描述"):1000));
				String costSubDesc=ExcelUtil.getCellValue(cell);
				if( null == costSubDesc) {
					messageStrb.append("第" + i +"行数据没有费用子项名称，请检查。<br>"); 
					continue ;
				}
				costSub.setCostSubdesc(costSubDesc) ;
				
				cell = row.getCell((int) (titlemap.get("费用别名") != null ? titlemap.get("费用别名"):1000));
				
				String costSubAlias = ExcelUtil.getCellValue(cell) ;
				if(StringUtils.hasLength(costSubAlias)){
					costSub.setCostSubAlias(costSubAlias);
				} else {
					costSub.setCostSubAlias(costSub.getCostSubdesc()) ;
				}
				
				cell = row.getCell((int) (titlemap.get("费用类别") != null ? titlemap.get("费用类别"):1000));
				String parcostCateCode = mapExp.get(ExcelUtil.getCellValue(cell)) == null ? null : mapExp.get(ExcelUtil.getCellValue(cell)).toString() ;
				costSub.setParcostCatecode(parcostCateCode);
				cell = row.getCell((int) (titlemap.get("费用五大类") != null ? titlemap.get("费用五大类"):1000));
				String dccCode = mapExpF.get(ExcelUtil.getCellValue(cell)) == null ? null : mapExpF.get(ExcelUtil.getCellValue(cell)).toString() ;
				costSub.setDccCode(dccCode);
				
				cell = row.getCell((int) (titlemap.get("对照医嘱表费用编码") != null ? titlemap.get("对照医嘱表费用编码"):1000));
				costSub.setOrderScode(ExcelUtil.getCellValue(cell));
				
				cell = row.getCell((int) (titlemap.get("是否费用明细：1不参与总费用计算，0参与总费用计算") != null ? titlemap.get("是否费用明细：1不参与总费用计算，0参与总费用计算"):1000));
				costSub.setIsDetail(ExcelUtil.getCellValue(cell));

				cell = row.getCell((int) (titlemap.get("质控费用编码") != null ? titlemap.get("质控费用编码"):1000));
				costSub.setCostCodeQuality(ExcelUtil.getCellValue(cell));
				costSubApplication.creatCostSub(costSub);
				rowCnt++;
			}
			messageStrb.append("导入完成，共导入"+rowCnt+"条数据!");
		} catch (Exception e) {
			e.printStackTrace();
			messageStrb.append("导入第" + (rowCnt+1) +"行数据时报错，导入终止。<br>");
			return InvokeResult.failure(messageStrb.toString()) ;
		} finally {
			ExcelUtil.deleteFile(filePath) ;
		}
		return InvokeResult.success(messageStrb.toString()) ;
	}
	

	@Override
	public InvokeResult doctorInfoImport(String filePath) {
		message="";
		StringBuffer strb = new StringBuffer() ;
		GlobalData.percent=0;
		detail="";
		String errorRow = "0";
		String errorCell="0";
		
		// 查询科室组 科室 病区信息 并转成map key:value -> desc:code
		List<DepGroupDTO> depgroupList = depGroupFacade.findAllDepGroup() ;
		List<Department> deppartmentList = departmentApplication.findAllDepartment() ;
		List<Ward> wardList = wardApplication.findAllWard() ;
		Map<String,String> depgroupMap = new HashMap<>() ;
		Map<String,String> departmentMap = new HashMap<>() ;
		Map<String,String> wardMap = new HashMap<>() ;
		for(DepGroupDTO depgroup : depgroupList) {
			depgroupMap.put(depgroup.getDepGroupDesc(), depgroup.getDepGroupCode()) ;
		}
		for(Department department : deppartmentList) {
			departmentMap.put(department.getDepName(),department.getDepCode() ) ;
		}
		for(Ward ward : wardList) {
			wardMap.put(ward.getWardDesc(), ward.getWardCode()) ;
		}
		// 查询所有医师信息
		List<ClinicGroup> clinicGroupList = clinicGroupApplication.findAllClinicGroup();
		
		Sheet sheet=null;
		Row row=null;
		Row firstrow=null;
		Cell cell=null;
		
		//读取表单数据		
		sheet = ExcelUtil.readExcelSheet(filePath, 0) ;
		firstrow = sheet.getRow(0);
		int colNum = firstrow.getLastCellNum(); 
		String[] title = new String[colNum];
		
		// 获取表头信息
		for (int firstnumCells = 0; firstnumCells < firstrow.getLastCellNum(); firstnumCells++) {
			cell = firstrow.getCell((short) firstnumCells);
			if(cell == null) {
				title[firstnumCells] = "";
			} else {
				title[firstnumCells] = cell.getStringCellValue();
				detail = cell.getStringCellValue();
			}
		}
		
		// 开始解析保存各行数据
		int rowCnt=0;
		try {
			for (int numRows = 1; numRows <= sheet.getLastRowNum(); numRows++) {
				row = sheet.getRow(numRows);
				if(ExcelUtil.isRowEmpty(row)) {
					continue ;
				}
				errorRow = String.valueOf(numRows+1);
				ClinicGroup doctor = new ClinicGroup() ;
				for (int numCells = 0; numCells < row.getLastCellNum(); numCells++) {
					cell = row.getCell((short) numCells);
					if(cell == null) {
						continue ;
					}
					String aaString=null;
					aaString = title[numCells];
					errorCell = String.valueOf(numCells+1);
					switch(aaString){
						case "科室名称": {
							String code = departmentMap.get(ExcelUtil.getCellValue(cell)) ;
							if(null != code) {
								doctor.setParDepCode(code);
							} else {
								strb.append("第"+errorRow+"行 "+"第"+errorCell+"列名称对应的编码未找到 </br>");
							}
							break ;
						}
						case "医师编码（必填）": {
							// 判断是否为空
							if("".equals(ExcelUtil.getCellValue(cell))) {
								strb.append("第"+errorRow+"行 "+"第"+errorCell+"列数据为空，该行未保存  </br>");
								continue ;
							}
							doctor.setGroupCode(ExcelUtil.getCellValue(cell));
							break ;
						}
						case "医师名称（必填）": {
							// 判断是否为空
							if("".equals(ExcelUtil.getCellValue(cell))) {
								strb.append("第"+errorRow+"行 "+"第"+errorCell+"列数据为空，该行未保存 </br>");
								continue ;
							}
							doctor.setGroupName(ExcelUtil.getCellValue(cell));
							break ;
						}
						case "医师类型": {
							doctor.setGroupType(ExcelUtil.getCellValue(cell));
							break ;
						}
				/*		case "科室组名称": {
							String code = depgroupMap.get(ExcelUtil.getCellValue(cell)) ;
							if(null != code) {
								doctor.setParDepGroupCode(code);
							} else {
								strb.append("第"+errorRow+"行 "+"第"+errorCell+"列名称对应的编码未找到 </br>");
							}
							break ;
						}*/
						case "是否有效(0:无效1.有效)": {
							// 正整数
							if("0".equals(ExcelUtil.getCellValue(cell)) || "1".equals(ExcelUtil.getCellValue(cell))) {
								doctor.setGroupActive(Integer.parseInt(ExcelUtil.getCellValue(cell)));
							} else {
								strb.append("第"+errorRow+"行 "+"第"+errorCell+"列不是合法数字 </br>");
							}
							break ;
						}
						case "显示顺序": {
							// 正整数
							Integer groupOrder = 0;
							if(ExcelUtil.getCellValue(cell)!=null && ExcelUtil.getCellValue(cell).matches("^\\d+$")) {
								String order = ExcelUtil.getCellValue(cell);
								if(clinicGroupApplication.isGroupOrderExist(order, null)){
									groupOrder = clinicGroupApplication.getMaxOrder()+1;
									doctor.setGroupOrder(groupOrder.toString());
									strb.append("第"+errorRow+"行 "+"显示顺序已存在，序号更新为"+groupOrder+" </br>");
								}else{
									doctor.setGroupOrder(order);
								}
							} else {
								groupOrder = clinicGroupApplication.getMaxOrder()+1;
								doctor.setGroupOrder(groupOrder.toString());
								strb.append("第"+errorRow+"行 "+"第"+errorCell+"列不是合法数字 ，序号更新为"+groupOrder+"</br>");
							}
							break ;
						}
						case "病区名称": {
							String code = wardMap.get(ExcelUtil.getCellValue(cell)) ;
							if(null != code) {
								doctor.setParWardCode(code);
							} else {
								strb.append("第"+errorRow+"行 "+"第"+errorCell+"列名称对应的编码未找到 </br>");
							}
							break ;
						}
					}
					String depCode = doctor.getParDepCode()==null?"":doctor.getParDepCode().toString().trim();
					String depGroupCode = departmentApplication.getDepGroupByDepCode(depCode);
					if(null != depGroupCode) {
						doctor.setParDepGroupCode(depGroupCode);
					}else{
						strb.append("第"+errorRow+"行科室找不到对应的科室组编码，请在科室表中维护  </br>");
					}
				}
				doctor.setId(UUID.randomUUID().toString().replaceAll("-", "")) ;
				if(StringUtils.hasLength(doctor.getGroupCode())&&StringUtils.hasLength(doctor.getGroupName())) {
					// 保存行数据 根据groupCode更新，主键是id
					if(clinicGroupList.contains(doctor)) {
						clinicGroupApplication.updateClinicGroupByDocCode(doctor,true) ;
					} else {
						clinicGroupApplication.creatClinicGroup(doctor) ;
					}
					clinicGroupList.add(doctor);
					rowCnt++;
				} else {
					strb.append("第"+errorRow+"行数据编码或名字为空，未保存 </br>");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			strb.append("第" + (errorRow) +"行数据导入时报错，导入终止。<br>"); 
			return InvokeResult.failure(strb.toString());
		} finally {
			ExcelUtil.deleteFile(filePath);
		}
		if(strb.length() != 0) {
			message =strb.toString() ;
		} else {
			message = "导入完成，共导入"+rowCnt+"条数据!" ;
		}
		return InvokeResult.success(message);
	}
	

	@Override
	public InvokeResult wardImport(String filePath) {
		// 查询所有科室
		List<Department> deppartmentList = departmentApplication.findAllDepartment() ;
		// 用于保存科室所在科室组
		Map<String,String> depDepgroupMap = new HashMap<>() ;
		// 将描述映射成编码
		Map<String,String> departmentMap = new HashMap<>() ;
		for(Department department : deppartmentList) {
			depDepgroupMap.put(department.getDepCode(), department.getParDepGroupCode()) ;
			departmentMap.put(department.getDepName(), department.getDepCode()) ;
		}
		int maxOrder = wardApplication.findMaxWardOrder() ;
		
		StringBuffer messageStrb = new StringBuffer();//返回前台的信息
		Sheet sheet = ExcelUtil.readExcelSheet(filePath,0);
		int rowNum=sheet.getLastRowNum();//行数
		Row row = null ;
		// 存放文件的表头位置
		Map<String,Object> titlemap = new HashMap<>();
		// 标题行
		Row headrow = sheet.getRow(0);
		int headCount = headrow.getLastCellNum();
		Cell cell=null;
		for (int i = 0; i < headCount; i++) {
			cell = headrow.getCell((short) i);
			titlemap.put(cell.getStringCellValue(), i);
		}
		int rowCnt=0;
		try {
			messageStrb.setLength(0);
			for(int i = 1 ; i <= rowNum ; i++) {
				row=sheet.getRow(i);
				// 该行为空时解析下一行
				if(ExcelUtil.isRowEmpty(row)) {
					continue ;
				}
				Ward ward=new Ward();
				cell = row.getCell((int) (titlemap.get("病区编码") != null ? titlemap.get("病区编码"):1000));
				String wardCode=ExcelUtil.getCellValue(cell);
				if( null == wardCode) {
					messageStrb.append("第" + (i) +"行数据没有病区代码，请检查。<br>"); 
					continue ;
				}
				ward.setWardCode(wardCode);
				cell = row.getCell((int) (titlemap.get("病区名称") != null ? titlemap.get("病区名称"):1000));
				String wardDesc=ExcelUtil.getCellValue(cell);
				if( null == wardDesc) {
					messageStrb.append("第" + (i) +"行数据没有病区名称，请检查。<br>"); 
					continue ;
				}
				ward.setWardDesc(wardDesc) ;
				cell = row.getCell((int) (titlemap.get("所属科室") != null ? titlemap.get("所属科室"):1000));
				String depCode = departmentMap.get(ExcelUtil.getCellValue(cell)) ;
				if(null == depCode) {
					messageStrb.append("第" + (i) +"行科室描述未找到编码,该行未保存<br>"); 
					continue ;
				} else {
					ward.setDepCode(depCode);
				}
				cell = row.getCell((int) (titlemap.get("病区备注") != null ? titlemap.get("病区备注"):1000));
				ward.setWardResume(ExcelUtil.getCellValue(cell));
				
				cell = row.getCell((int) (titlemap.get("显示顺序") != null ? titlemap.get("显示顺序"):1000));
				// 正整数
				if(cell==null) {
					maxOrder+=1 ;
					ward.setWardOrder(maxOrder) ;
				} else {
					if(ExcelUtil.getCellValue(cell).matches("^\\d+$")) {
						Integer wardOrder = Integer.parseInt(ExcelUtil.getCellValue(cell)) ;
						if(maxOrder<wardOrder) {
							maxOrder = wardOrder;
						}
						ward.setWardOrder(wardOrder);
					} else {
						messageStrb.append("第" + (i) +"行数据顺序数字不是非负整数。<br>"); 
					}
				}
				// 病区所在科室组
				ward.setDepGroupCode(depDepgroupMap.get(ward.getDepCode()));
				wardApplication.creatWard(ward);
				rowCnt++;
			}
			messageStrb.append("成功导入"+rowCnt+"条数据!<br>");
		} catch (Exception e) {
			e.printStackTrace();
			messageStrb.append("导入第" + (rowCnt+1) +"行数据时报错，导入终止。<br>");
			return InvokeResult.failure(messageStrb.toString()) ;
		} finally {
			ExcelUtil.deleteFile(filePath) ;
		}
		return InvokeResult.success(messageStrb.toString()) ;
	}
	
    /**
     * 
     * @ClassName: parseMrdata  
     * @Description ：    解析获取首页数据
     * @Date: 2018年4月3日 下午3:20:17  
     * @Author mazhaoyan 
     * @Version 2.5.0 DHC-DRGs
     */
	public class ParseMrdataXML extends Thread{
		private Element node;
		private Storage storage = null;
		private Map<String,Object> initMap;
		private Map<String,Object> xPathMap;
		
		public ParseMrdataXML(Element node,Storage storage,Map<String,Object> initMap,Map<String,Object> xPathMap){
			this.node = node;
			this.storage = storage;
			this.initMap = initMap;
			this.xPathMap = xPathMap;
		}
		
		public void run() {
			Map<String, Object> caseMap = xPathParseFacade.parseXmlNode(node,initMap,xPathMap);
			try {
				if(caseMap!=null) {
					storage.push(caseMap);//生产
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
	    } 
	}
	
	/**
     * 
     * @ClassName: parseMrdata  
     * @Description ：    解析获取首页数据
     * @Date: 2018年4月3日 下午3:20:17  
     * @Author mazhaoyan 
     * @Version 2.5.0 DHC-DRGs
     */
	public class ParseMrdataOther extends Thread{
		private Object[] colArr;
		private Storage storage = null;
		private Map<String,Object> initMap;
		
		public ParseMrdataOther(Object[] colArr, Storage storage, Map<String, Object> initMap) {
			this.colArr = colArr;
			this.storage = storage;
			this.initMap = initMap;
		}

		public void run() {
			Map<String, Object> caseMap = parseRowData(colArr,initMap);
			try {
				storage.push(caseMap);//生产
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
	    } 
	}
	
	/**
	 * 
	 * @ClassName: SaveMrData  
	 * @Description ： 保存首页数据
	 * @Date: 2018年4月3日 下午3:21:34  
	 * @Author mazhaoyan 
	 * @Version 2.5.0 DHC-DRGs
	 */
	public class SaveMrData extends Thread{
		private Storage storage = null;
		private Map<String,Object> initMap;
		
		public SaveMrData(Storage storage,Map<String,Object> initMap){
			this.storage = storage;
			this.initMap = initMap;
		}
		public void run(){
			try {
				synchronized (consumeCnt) {
					printProgress(allCnt,++consumeCnt);
				}
				//消费
				if(storage!=null) {
				    Map<String, Object> caseMap = storage.pop();
					if(caseMap!=null){
						String errInfo = fileUploadApplication.saveCaseInfo(caseMap);//保存
						if(StringUtils.hasLength(errInfo)){
							//写入log日志
							String pMainIndex = caseMap.get("pMainIndex").toString();
							logger.error(pMainIndex+" "+errInfo);
						}else{
							assembleAndGroup(caseMap,initMap);
						}
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();	
			}
		}
	}
	/**
	 * 
	 * @Description: 分组异常数据系统导出
	 * @author shaozhiyuan 
	 * @date 2018年5月16日  
	 * @version V3.1.0
	 */
	@Override
	public Map<String,Object> getAbnomalGroupCase(String mrNumber) {
		Map<String,Object> abnomalGroupCaseData=new HashMap<String,Object>();
		//查询病案号是否在数据库中存在，并返回不存在数据库中的病案号到前台
		String notInCaseNumberStr="";
		String inCaseNumberStr="";
		int abnomalSum=0;
		if(!"".equals(mrNumber)&&mrNumber.contains("&")){
			//多条录入
			mrNumber = mrNumber.replaceAll("\\s*", "");// 去除空格
			String[] num = mrNumber.split("\\&");
			for(int i=0;i<num.length;i++){
				String obj=num[i]==null?"":num[i].toString().trim();
				Boolean numIsExits = fileUploadApplication.findAbnomalGroupCase(obj);//查询病案号是否存在于数据库中
				if(numIsExits){
					inCaseNumberStr+="'"+obj+"',";
				}else{
					notInCaseNumberStr+=obj+",";
				}
			}
			//当字符串包含逗号时删除最后一个逗号
			if(inCaseNumberStr.length()>1){
				inCaseNumberStr=inCaseNumberStr.substring(0, inCaseNumberStr.length()-1);
			}
			if(notInCaseNumberStr.length()>1){
				notInCaseNumberStr=notInCaseNumberStr.substring(0, notInCaseNumberStr.length()-1);
			}
		}else{
			//单条录入
			Boolean numIsExits = fileUploadApplication.findAbnomalGroupCase(mrNumber);//查询病案号是否存在于数据库中
			if(numIsExits){
				inCaseNumberStr="'"+mrNumber+"'";
			}else{
				notInCaseNumberStr=mrNumber;
			}
		}
		//获取分组异常数据列表详细信息 
		List<Map<String, Object>> abnomalGroupCaseList=new ArrayList<Map<String, Object>>();
		if(inCaseNumberStr!=""){
			abnomalGroupCaseList=fileUploadApplication.findAbnomalGroupCaseList(inCaseNumberStr);
			//计算总数
			abnomalSum=abnomalGroupCaseList.size();
		}
		//区分是否手术或操作
		Boolean checkIsOper=fileUploadApplication.checkIsOper();
		abnomalGroupCaseData.put("abnomalSum", abnomalSum);
		abnomalGroupCaseData.put("notInCaseNumber", notInCaseNumberStr);
		abnomalGroupCaseData.put("abnomalGroupCaseList", abnomalGroupCaseList);
		abnomalGroupCaseData.put("isOper", checkIsOper);
		return abnomalGroupCaseData;
	}


	public Map<String,String>  processCodeAndDesc(Map<String,String> mapObj,Map<String,Object> codeMap,Map<String,Object> descMap,String monitorType) throws Exception {
		String code = mapObj.get("code") ;
		String desc = mapObj.get("desc") ;
		String hospCode = mapObj.get("hospCode") ;
		String parDepCode = mapObj.get("depCode") ;
		// 实体表的操作 插入-insert、 更新-update
		String action = null ;
		// 空格处理
		if(StringUtils.hasLength(desc)) {
			desc = desc.replaceAll("\\s*", "") ;
		}

		// 编码描述都有
		if(StringUtils.hasLength(code) && StringUtils.hasLength(desc)){
			// 编码不变描述变了:采用新的描述，更新实体表。
			if(codeMap.containsKey(code) && !descMap.containsKey(desc)){
				action = "update" ;
				// 编码变了描述不变:新增记录
			} else if(!codeMap.containsKey(code) && descMap.containsKey(desc)){
				action = "insert" ;
				// 编码描述都变了(ps:实体表中不存在):实体表中新增。
			} else if(!codeMap.containsKey(code) && !descMap.containsKey(desc)){
				action = "insert" ;
			}
			// 有编码无描述:
		} else if(StringUtils.hasLength(code) && !StringUtils.hasLength(desc)) {
			// 编码变了：实体表新增，采用默认描述，保存到首页。
			if(!codeMap.containsKey(code)){
				desc = "未知描述("+code+")" ;
				action = "insert" ;
				// 编码不变：从实体表中获取描述,保存到首页。
			} else {
				desc = (String)codeMap.get(code) ;
			}
			// 有描述无编码:
		} else if(!StringUtils.hasLength(code) && StringUtils.hasLength(desc)) {
			// 描述有变化(ps:实体表中找不到描述):unknown-uuid作为编码,保存到首页,保存实体表。
			if(!descMap.containsKey(desc)) {
				code = "unknown-"+UUID.randomUUID() ;
				action = "insert" ;
			} else {
				// 描述无变化(ps:实体表中可以找到描述):根据描述查询编码，保存到首页。
				code = descMap.get(desc)+"" ;
			}
			// 描述编码均没有
		} else {
			// 采用默认的编码和描述
			code = "unknown" ;
			desc = "未知描述" ;
			if(codeMap.containsKey(code)){
				action  = "update" ;
			} else {
				action  = "insert" ;
			}
		}
//		System.err.println("=====================action========================= : " + action);
		if(null != action) {
			if("dep".equals(monitorType)) {
				Department department = new Department() ;
				department.setDepCode(code);
				department.setDepName(desc);
				if("update".equals(action)) {
					departmentApplication.updateDepartment(department);
				} else if("insert".equals(action)) {
					department.setParHospCode(hospCode);
					// 判断是否已有新增科室组
					if(!mapObj.containsKey("parDepGroupCode")){
						DepGroupDTO depGroupDTO = new DepGroupDTO() ;
						depGroupDTO.setDepGroupCode("XZKSKSZ");
						depGroupDTO.setDepGroupDesc("新增科室科室组");
						depGroupFacade.creatDepGroup(depGroupDTO) ;
					}
					department.setParDepGroupCode("XZKSKSZ");
					departmentApplication.creatDepartment(department); //保存科室信息
				}
			} else if("ward".equals(monitorType)) {
				Ward ward = new Ward() ;
				ward.setWardCode(code);
				ward.setWardDesc(desc);
				ward.setDepCode(parDepCode==null?"unknown":parDepCode);
				if("update".equals(action)) {
					wardApplication.updateWard(ward);
				} else if("insert".equals(action)) {
					wardApplication.creatWard(ward);
				}
			} else if("doctor".equals(monitorType)) {
				ClinicGroup clinicGroup = new ClinicGroup() ;
				clinicGroup.setGroupCode(code) ;
				clinicGroup.setGroupName(desc);
				if("update".equals(action)) {
					clinicGroupApplication.updateClinicGroupByDocCode(clinicGroup,false);
				} else if("insert".equals(action)) {
					clinicGroup.setId(UUID.randomUUID().toString());
					clinicGroupApplication.creatClinicGroup(clinicGroup);
				}
			}
			codeMap.put(code,desc) ;
			descMap.put(desc,code) ;
		}
		Map<String,String> resultMap = new HashMap<>() ;
		resultMap.put("code", code);
		resultMap.put("desc", desc);
		return resultMap ;
	}
	
	@Override
	public InvokeResult saveConfirmFlag(String datefrom, String dateto) {
		int count = fileUploadApplication.saveConfirmFlag( datefrom, dateto);
		if(count > 0){
			return InvokeResult.success();
		}
		return InvokeResult.failure("此时间段无病例数据");
	}

}